欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET连接数据库

程序员文章站 2022-08-11 11:05:59
  (一)、在Web.Config中创建连接字符串: 1、

 

(一)、在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");