C#连接Access与SQL Server

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 something
16 }
17 
18 cnn.Close();
复制代码

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


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

然后

复制代码
 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 something
15             }
16             conn.Close();
复制代码               本文由 whchina(江城老温)原创发布,转载请注明出处,江城老温 as a thinker。

你可能感兴趣的:(C#学习笔记)