.net串連sql server主要方式有:SqlClient、OleDB、ODBC
1、SqlClient專用於微軟的MSSQL,因此SqlClient速度會塊些。
串連串的形式:"server=localhost;database=northwind;uid=sa;pwd=;"
或者"Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind"
System.Data.SqlClient.SqlConnection conn = new SqlConnection("server=.;database=master;uid=sa;pwd=;");<br />conn.Open();<br />SqlCommand cmd=new SqlCommand("select * from tb",conn);<br />System.Data.SqlClient.SqlDataReader myDR=cmd.ExecuteReader();<br />while (myDR.Read()) //如果未到尾記錄<br />{<br /> Response.Write(myDR.GetString(0)); //0所代表的是第一個欄位,然後下一個是1<br /> Response.Write("<br>");<br />}<br />myDR.close();<br />conn.close(); </p><p>
2、OleDB
OleDbConnection nwindConn = new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Integrated"+<br />" Security=SSPI;Initial Catalog=northwind"); </p><p>OleDbCommand salesCMD = new OleDbCommand("select * from tb", nwindConn);</p><p>nwindConn.Open();</p><p>OleDbDataReader myReader = salesCMD.ExecuteReader();</p><p>while (myReader.Read())<br />{<br /> Console.WriteLine("/t{0}, ${1}", myReader.GetString(0), myReader.GetDecimal(1));<br />}</p><p>myReader.Close();<br />nwindConn.Close();<br />
3、ODBC
OdbcConnection nwindConn = new OdbcConnection("Driver={SQL Server};Server=localhost;Trusted_Connection=yes;" +<br /> "Database=northwind");<br />nwindConn.Open();</p><p>OdbcCommand salesCMD = new OdbcCommand("select * from tb", nwindConn);</p><p>OdbcDataReader myReader = salesCMD.ExecuteReader();<br />while (myReader.Read())<br />{<br /> Console.WriteLine("/t{0}, ${1}", myReader.GetString(0), myReader.GetDecimal(1));<br />}</p><p>myReader.Close();<br />nwindConn.Close();