ASP.NET中操作SQL数据库(连接字符串的配置及获取
编程学习 2021-07-04 22:40www.dzhlxh.cn编程入门
要想在ASP.NET中操作SQL数据库首先需要在WebConfig中配置数据库连接字符串,之后在.cs文件中获取连接字符串,具体的配置及获取方法如下,感兴趣的朋友可以参考下哈
在WebConfig中配置数据库连接字符串,代码如下:
<connectionStrings>
<add name="ConnectionString" connectionString="user id=用户名;password=密码;initial catalog=数据库名称;data source=服务器名称"/>
</connectionStrings>
然后在Webform_1.aspx.cs里面获取连接字符串,要添加如下引用;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
代码:
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
ConnectDB();
}
private void ConnectDB()
{
string ConString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
con = new SqlConnection(ConString);
con.Open();
SqlCommand com = new SqlCommand();
SqlDataReader sdr;
string sqlstr = "select * from item";
com.CommandText = sqlstr;
com.Connection = con;
sdr = com.ExecuteReader();
while (sdr.Read())
{
Response.Write(sdr["字段名"].ToString()+"</br>");
}
sdr.Close();
sdr = null;
}
这样就可以了,非常简单,初学asp.net ,希望朋友们多指教,感激不尽!
代码如下:
<connectionStrings>
<add name="ConnectionString" connectionString="user id=用户名;password=密码;initial catalog=数据库名称;data source=服务器名称"/>
</connectionStrings>
然后在Webform_1.aspx.cs里面获取连接字符串,要添加如下引用;
代码如下:
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
代码:
代码如下:
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
ConnectDB();
}
private void ConnectDB()
{
string ConString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
con = new SqlConnection(ConString);
con.Open();
SqlCommand com = new SqlCommand();
SqlDataReader sdr;
string sqlstr = "select * from item";
com.CommandText = sqlstr;
com.Connection = con;
sdr = com.ExecuteReader();
while (sdr.Read())
{
Response.Write(sdr["字段名"].ToString()+"</br>");
}
sdr.Close();
sdr = null;
}
这样就可以了,非常简单,初学asp.net ,希望朋友们多指教,感激不尽!