C# 連接數(shù)據(jù)庫
一、SQL SERVER 連接字符串語法:
1、SQL SERVER驗(yàn)證(兩種寫法)(安全連接)
string connStr = "Data Source=.;Initial Catalog=DatabaseName;User Id=sa;Password=123"; 或 string connStr = "server=.;database=DatabaseName;uid=sa;pwd=123";
即:Data Source <=> server
Initial Catalog <=> database
User Id <=> uid
Password <=> pwd
2、windows驗(yàn)證(可信連接)
string connStr = "Data Source=.;Initial Catalog=DatabaseName;Integrated Security=SSPI"; 或 string connStr = "Data Source=.;Initial Catalog=DatabaseName;Integrated Security=True"; 或 string connStr = "Data Source=.;Initial Catalog=DatabaseName;Trusted_Connection=True";
注:如果服務(wù)器是本地,可以用 local 或 .(一個(gè)點(diǎn)) 表示,如果是遠(yuǎn)程服務(wù)器,則用 IP,端口 表示。
連接字符串中的鍵值對不區(qū)分大小寫。
二、配置文件中存儲(chǔ)方式
可以把連接字符串保存到配置文件中(App.config)
1、配置到<connectionStrings>節(jié)點(diǎn)中(推薦):
<add name="connStr" connectionString="server=.;database=test;uid=sa;pwd=123;" providerName="System.Data.SqlClient"/>
2、也可以配置到<appSettings>節(jié)點(diǎn):
<add key="connStr" value="server=.;database=test;uid=sa;pwd=123;"/>
讀取配置文件中的連接字符串
1、首先,在項(xiàng)目下的“引用”中,點(diǎn)擊右鍵——添加引用,添加:System.Configuration。
2、在程序最上面,添加:using System.Configuration;
3、讀取連接字符串:
conn.ConnectionString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;//<ConnectionStrings>節(jié)點(diǎn)中讀取方法 conn.ConnectionString = ConfigurationManager.AppSettings["connStr"].ToString();//<AppSettings>節(jié)點(diǎn)中讀取方法
連接對象的創(chuàng)建
string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; //創(chuàng)建連接對象的第一種方式(推薦) SqlConnection conn = new SqlConnection(connStr); //創(chuàng)建連接對象的第二種方式 SqlConnection conn = new SqlConnection(); conn.ConnectionString = connStr;
使用using來釋放對象
//SqlConnection繼承于IDisposeable接口,可以使用using 來釋放對象 SqlConnection conn = null; using (conn = new SqlConnection(connStr)) { //代碼 } Console.WriteLine(conn.State);//Closed
加密/解密配置文件:
Configuration config = ConfigurationManager.OpenExeConfiguration("ConsoleApp10.exe"); //ConsoleApp10.exe為應(yīng)用程序名稱 ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection; if (section.SectionInformation.IsProtected) { // Remove encryption. section.SectionInformation.UnprotectSection(); } else { // Encrypt the section. section.SectionInformation.ProtectSection( "DataProtectionConfigurationProvider"); } // Save the current configuration. config.Save();
三、運(yùn)行時(shí)間測定(Stopwatch)
Stopwatch sw = new Stopwatch(); sw.Start(); //測試代碼 sw.Stop(); Console.WriteLine($"運(yùn)行時(shí)間:{sw.ElapsedMilliseconds}ms");
四、SqlCommand
Sq1Command介紹
重要屬性:
Connection:SqlCommand對象使用的SqlConnection
CommandText:獲取或設(shè)置要執(zhí)行的T-SQL語句或存儲(chǔ)過程名
CommandType:CommandType.Text--執(zhí)行的是一個(gè)Sql語向
CommandType.StoredProcedure--執(zhí)行的是一個(gè)存儲(chǔ)過程
Parameters:SqlCommand對象的命令參數(shù)集合 默認(rèn)空集合
Transaction:獲取或設(shè)置要在其中執(zhí)行的事務(wù)
創(chuàng)建(推薦使用第三種):
//1. SqlCommand cmd=newSqlCormand(); cmd.Connection=conn; cmd.CommandText=sql; //cmd.ConmandType=CommandTypeText;沒有必要的 //cmd.ConmandType=CommandTypeStoredProcedure;//如果是存儲(chǔ)過程,必須設(shè)置
//2. SqlCommandcmd1=new SqlCommand(sql); cmd1Connection=conn;
//3.sql語句 連接對象 推薦的 SqlCommand cmd2=newSqlConmand(sql,conn); //4.Connection對象 SqlCommandcmd3=connCreateConmand); cmd3ConmandText=sql; //5.事務(wù) string delSql="deletefrom UserInfos whereUserId>3"; //SqlCommand cmd4=newSqlCommand(delSql,conn,null);
五、SqlParameter
常用屬性
DbType 參數(shù)的SqlDbType(數(shù)據(jù)類型數(shù)據(jù)庫的類型而言)
Direction參數(shù)的類型:輸入輸出輸入輸出、返回值參數(shù)
ParameterName 參數(shù)的名稱
Size 最大大小 字節(jié)為單位
Value參數(shù)的值
SqlValue作為SQL類型的參數(shù)的值
構(gòu)造方法
1.參數(shù)
SqlParameter pral=new SqlParameter();
pral.ParameterName="@userName";//參數(shù)名
pra1.Sq1DbType=Sq1DbType.VarChar//數(shù)據(jù)類型
pra1.Value ="admin”;//參數(shù)值
pral.Size =20;//大小
2.參數(shù)名,值
SqlParameter para2=new SqlParameter("@Age",24);
3.參數(shù)名 SqlDbType
SqlParameter para3=new SqlParameter("@DeptId",SqlDbType.Int);
para3.Size =4;
para3.Value=3;
4.參數(shù)名 類型 大小
SqlParameter para4 =new SqlParameter("@UserPwd",SqlDbType.VarChar. 50);
para4.Value="123456”
5參數(shù)名稱 類型 大小 源列名(對應(yīng)DataTable中的列名)
SqlParameter para5 =new SqlParameter(“@UserName”,SqlDbType.VarChar,20.
"UName”);
SqlConmand cmd=new SqlConmand();
SqlDataReader介紹
定義:提供一種從SQLServer數(shù)據(jù)庫中讀取只進(jìn)的行流的方式。
特點(diǎn) 快速的、輕量級,只讀的,諞歷訪問每一行數(shù)據(jù)的數(shù)據(jù)流,向一個(gè)方向,一行一行的,不能
向后讀取,不能修改數(shù)據(jù)。
缺點(diǎn):不靈活,只適合數(shù)據(jù)小的情況,讀取數(shù)據(jù),一直占用連接
讀取方式:Read()獲取第一行的數(shù)據(jù),再次調(diào)用Read()方法,
當(dāng)調(diào)用Read()方法返回False時(shí),就表示不再有數(shù)據(jù)行。
注意:
連接對象一直保持Open狀態(tài),如果連接關(guān)閉,是不能讀取數(shù)據(jù)的。使用完成過后,應(yīng)該馬上調(diào)
用close()關(guān)閉,不然Reader對象會(huì)一直占用連接的。
創(chuàng)建方式:是不能直接構(gòu)造的,cmd.ExecuteReader()來創(chuàng)建。cmd.ExecuteReader
(CommandBehaviour.CloseConnection)---好處:關(guān)團(tuán)reader對象時(shí),就會(huì)自動(dòng)關(guān)閉連接。
讀取時(shí)盡量使用與數(shù)據(jù)庫字段類型相匹配的方法來取得對應(yīng)的值,會(huì)減少因類型不一致而增加
類型轉(zhuǎn)換操作性能損耗。
沒有讀取到末尾就要關(guān)閉reader對象時(shí),先調(diào)用cmdCancel(),然后再調(diào)用reader.Close().
cmd.ExecuteReader()獲取存儲(chǔ)過程的返回值或輸出參數(shù),先調(diào)用readerClose(),然后才能
獲取參數(shù)的值。
常用屬性:
Conection:獲取與Reader對象相關(guān)的SqlConnection
FiedCount:當(dāng)前行中的列數(shù)。
HasRows:reader是否包含一行還是多行。
IsClosedreader對象是否已關(guān)閉 true / false
Item[int]:列序號(hào),給定列序號(hào)的情況,獲取指定列的值dr[1] object
Item[String]列名,獲取指定列的值

浙公網(wǎng)安備 33010602011771號(hào)