C#基础-连接Access与SQL Server

2018-06-18 02:04:34来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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里添加连接字段

<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 something
15             }
16             conn.Close();

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:表达式计算器

下一篇:黑马程序员——ARC机制总结和用ARC建立模型