Asp.net 访问数据库的几种方式

ASP.NET中连接数据库的各种方法
连接SQL数据库的方法:
(一)、在Web.Config中创建连接字符串:
1、
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\grade.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
2、
<add name="sampleConnectionString" connectionString ="server=.\SQLEXPRESS;database=sample;uid=sa;pwd=123456;" providerName ="System.Data.SqlClient"/>
3、
<add name ="testConnectionString" connectionString ="Data Source=.\SQLEXPRESS;Initial Catalog=sample;Integrated Security=True;Persist Security Info=True;User ID=sa;Password=123456" providerName ="System.Data.SqlClient"/>
(二)、在aspx.cs中获取连接字符串:
1、
string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["sampleConnectionString"].ConnectionString;
2、
string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["sampleConnectionString"].ToString();
3、
string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["testConnectionString"].ToString();
(三)、将连接字符串直接写到页面里
1、
string strCon = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\grade.mdf;Integrated Security=True;User Instance=True";
2、
string strCon = "Data Source=.\\SQLEXPRESS;Initial Catalog=sample;Integrated Security=True;Persist Security Info=True;User ID=sa;Password=123456";
3、
string strCon = "server=.\\SQLEXPRESS;database=sample;uid=sa;pwd=123456";
连接Access数据库(yx.mdb)的方法:
(一)、在Web.Config中创建连接字符串:
<add name ="accessConnectionString" connectionString ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\yx.mdb" providerName ="System.Data.OleDb"/>
(二)、在aspx.cs中获取连接字符串:
1、
string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["accessConnectionString"].ToString();
2、
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|Datadirectory|\\yx.mdb";
3、
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/App_Data/yx.mdb");
注意:如果要连接Access2007版本里的数据库(Database1.accdb)时,用下面的方法连接:
string strCon = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + Server.MapPath("~/App_Data/Database1.accdb");
上一篇:Load Balancing 折半枚举大法好啊


下一篇:配置jdk相关的记录