.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=;"); conn.Open(); SqlCommand cmd=new SqlCommand("select * from tb",conn); System.Data.SqlClient.SqlDataReader myDR=cmd.ExecuteReader(); while (myDR.Read()) //如果未到尾记录 { Response.Write(myDR.GetString(0)); //0所代表的是第一个字段,然后下一个是1 Response.Write("<br>"); } myDR.close(); conn.close();
2、OleDB
OleDbConnection nwindConn = new OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Integrated"+ " Security=SSPI;Initial Catalog=northwind"); OleDbCommand salesCMD = new OleDbCommand("select * from tb", nwindConn); nwindConn.Open(); OleDbDataReader myReader = salesCMD.ExecuteReader(); while (myReader.Read()) { Console.WriteLine("/t{0}, ${1}", myReader.GetString(0), myReader.GetDecimal(1)); } myReader.Close(); nwindConn.Close();
3、ODBC
OdbcConnection nwindConn = new OdbcConnection("Driver={SQL Server};Server=localhost;Trusted_Connection=yes;" + "Database=northwind"); nwindConn.Open(); OdbcCommand salesCMD = new OdbcCommand("select * from tb", nwindConn); OdbcDataReader myReader = salesCMD.ExecuteReader(); while (myReader.Read()) { Console.WriteLine("/t{0}, ${1}", myReader.GetString(0), myReader.GetDecimal(1)); } myReader.Close(); nwindConn.Close();