当前位置:编程学习 > C#/ASP.NET >>

asp.net 连接sql数据库的方法

怎样连接最简便
答案:
//连接数据库的代码SQL  
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//数据库连接字符
String connectionString = "Server=127.0.0.1;Database=desschool;uid=sa;pwd=222;";
//要执行的Sql语句
String cmdText = "select * from test";
//建立连接
SqlConnection conn = new SqlConnection(connectionString);
//生成命名实例
SqlCommand command = new SqlCommand(cmdText, conn);
//生成数据集实例
DataSet dataSet = new DataSet();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = command;
//填充数据集
sqlDA.Fill(dataSet);
dgProShow.DataSource = dataSet;
//绑定控件
dgProShow.DataBind();

}
}
//在conn.aspx中加入代码:
//<asp:DataGrid runat="server" ID="dgProShow"></asp:DataGrid>
//这样就完成了对数据库的连接和读取操作。

上一个:ASP如何与SQL数据库用在一起?
下一个:ASP如何连接mysql数据库(不用DSN)?

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,