<span style="font-size:24px;">在要在应用程序中访问数据库中的数据,首先要建立连接。以下是应用程序与SQLServer数据库连接的代码及详细解释:</span>
<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace XMLRW
{
public partial class conn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//首先创建连接字符串,数据源:本地用“.”Initial Catalog 为连接数据库的名字;uid则为数据库名称,后面为数据库密码
string strcon = "Data Source=.;Initial Catalog = Message;uid = sa;pwd = 123123";
using (SqlConnection conn = new SqlConnection(strcon)) //使用using实例化连接
{
conn.Open(); //打开连接
SqlCommand comm = new SqlCommand();
comm.Connection = conn; //实例化SqlCommand类并将其与数据库连接
string sql = "select * from Menu"; //查询Menu的信息
comm.CommandText = sql; //与数据库查询连接
SqlDataAdapter sqlAdapter = new SqlDataAdapter(); //实例化适配器
sqlAdapter.SelectCommand = comm; //适配器与SqlCommand连接
conn.Close(); //关闭连接
}
}
}
}