你的位置:首页 > ASP.net教程

[ASP.net教程]C#连接Access与SQL Server(常用笔记1)

1.连接Access数据库

 1 string strConnection = "Provider=Microsoft.Ace.OleDb.12.0; Data Source=" + Server.MapPath("~\\App_Data\\db1.accdb"); 2  3 OleDbConnection cnn; 4 OleDbCommand cmd; 5 OleDbDataReader datar; 6  7 string str_sql = "select * from T_product where ID=0;"; 8 cnn = new OleDbConnection(strConnection); 9 cnn.Open();10 cmd = new OleDbCommand(str_sql, cnn);11 datar = cmd.ExecuteReader();12 13 while (datar.Read())14 {15   //do something16 }17 18 cnn.Close();

2.连接SQL Server数据库
首先在Webconfig里添加连接字段

<connectionStrings>  <add name="ApplicationServices"     connectionString="Server=(local);Integrated Security=SSPI;database=TestServer;uid=***;pwd=***" providerName="System.Data.SqlClient"/> </connectionStrings>

然后

 1 string setting = "ApplicationServices"; 2 var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings[setting]; 3  4       SqlConnection conn = new SqlConnection(connString.ConnectionString); 5       SqlCommand cmd; 6       SqlDataReader datar; 7       string str_sql = "select * from T_category;"; 8       conn.Open(); 9       cmd = new SqlCommand(str_sql, conn);10       datar = cmd.ExecuteReader();11       while (datar.Read())12 13       {14          // do something15       }16       conn.Close();