Asp.net使用SqlConnection对象连接SQL Server数据库

1.首先声明命名空间

using System.Data.SqlClient;

2.设置好数据库的连接字符串

	string ConnectionString="Server=服务器名;user id=用户名;pwd=密码;data source=数据库名";

1)选用windows身份验证是,要在连接字符串中添加Integrated Security = true或者Integrated Security = SSPI,这是就不需要用户名和密码了,代码为
string connectionString = "Server=DESKTOP-C9D95LA\\SQLEXPRESS;Integrated Security=SSPI;DataBase=mysql";
2)选用Sql Server身份验证时,要提供user id,以及pwd,如果使用这种模式登陆时,需要在Sql server 2008中更改一下设置。
具体步骤如下:
先使用windows身份验证模式登陆,登陆之后,将鼠标放置在服务器名处,鼠标右键选择属性,之后找到安全性一栏,将服务器身份验证改为SQL Server和Windows身份验证模式,点击确定,之后重新启动Sql server.

3.建立数据库连接对象并打开连接

 SqlConnection cnn = new SqlConnection(connectionString);
        cnn.Open();

4.读取数据

1.提供SQL语句

string _sql = "select * from student";

2.建立sqlCommand对象

SqlCommand cmd = new SqlCommand(_sql,cnn);

3.读取数据并关闭连接:

        SqlDataReader datar = cmd.ExecuteReader();
        while (datar.Read()) {
            Response.Write(datar["sname"]+"</br>");
        }
        cnn.Close();

5.在Web.config文件中配置数据库连接的字符串

1)在Web.config文件中添加以下代码:

  <connectionStrings>
<add name="OnlineTestConnectionString" connectionString="Data Source=DESKTOP-C9D95LA\SQLEXPRESS;AttachDbFilename=&quot;D:\SQL serve 2008 shared\MSSQL10.SQLEXPRESS\MSSQL\DATA\OnlineTest.mdf&quot;;Integrated Security=True"
  providerName="System.Data.SqlClient" />
 </connectionStrings>

2)获取web.config文件中与数据库连接的字符串:
首先使用命名空间:using System.Configuration;
接着获取数据库连接的字符串:

 string connectionStr = ConfigurationManager.ConnectionStrings["OnlineTestConnectionString"].ConnectionString;

3)建立连接:
SqlConnection cnn = new SqlConnection(connectionString);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值