標籤:
Asp.net web串連資料庫步驟。
一、 建立一個web工程。
1.檔案->添加->建立網站->asp.net web網站Winform表單。
2.建立好的網站最下面有個web.config檔案,在個檔案裡面找到資料庫連接字串,如下:
<connectionStrings>
<add name="DefaultConnection" connectionString="
Data Source=PC-20160403SKQW\SQLEXPRESS;Initial Catalog=CAD;uid=sa;pwd=123456;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
3.其中Data Source是資料庫執行個體名稱,如果是網路資料庫則Data Source=ip,連接埠;例如Data Source= 192.1608.68.12,2000;
如果是本機使用者的話,Data Source=資料庫執行個體名稱;例如Data Source= PC-20160403SKQW\SQLEXPRESS;可以在登陸資料資料庫的時候看到執行個體名稱,如:
4. Initial Catalog=資料庫名稱;uid=登陸賬戶;pwd=密碼;Integrated Security=True
二、 代碼實現讀取。
建立一個winform表單test.aspx,在test.aspx.cs裡面編寫代碼
using System.Configuration;
using System.Data.SqlClient;
protected void Page_Load(object sender, EventArgs e)
{
//1.擷取設定檔裡面配置的資料庫連接字串
String connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
SqlConnection connection =new SqlConnection(connectionString);
// Create the Command and Parameter objects.
//2.sql語句
string queryString =
"SELECT * from Solution";
SqlCommand command = new SqlCommand(queryString, connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
//3.開啟串連
connection.Open();
//4.執行sql語句
SqlDataReader reader = command.ExecuteReader();
//5.查看返回結果
while (reader.Read())
{
//Console.WriteLine("\t{0}\t{1}\t{2}",
// reader[0], reader[1], reader[2]);
String a = reader[0].ToString();
Console.WriteLine(a);
}
//6.關閉串連
reader.Close();
}
asp.net串連資料庫