pro" />
当前位置:文档之家› 数据库连接代码

数据库连接代码

连接数据库:
命名空间:using System.Data.SqlClient;
<asp:SqlDataSource ID="SqlDataSource1"runat="server"></asp:SqlDataSource>
protected void Page_Load(object sender, EventArgs e)
{
//实现数据库连接
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=localhost;Initial Catalog=student;Integrated Security=True ";//连接数据库字符串
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
mandType = CommandType.Text;//配置类型
mandText = "select * from users";//sql语句
SqlDataReader sr = cmd.ExecuteReader();
while (sr.Read())
{
Response.Write( "<br>"+"userid:" + sr.GetInt32(0));
}
sr.NextResult();
while (sr.Read())
{
Response.Write("<br>" + "userName:" + sr.GetString(0));
}
sr.Close();
conn.Dispose();
conn.Close();
}
在原数据表中新增一条数据:
<asp:Button runat="server"ID="button1"Text="新增"OnClick="btAdd_Click"/>
protected void btAdd_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=localhost;Initial Catalog=student;Integrated Security=True ";//连接数据库字符串
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
mandType = CommandType.Text;
mandText = "insert into users values (4,'ddd')";
int rt = cmd.ExecuteNonQuery();
if (rt >= 0)
{
Response.Write("新增成功!");
}
}
在原有数据表中修改一条数据:
<asp:Button runat="server"ID="button2"Text="修改"OnClick="btUpdate_Click"/>
protected void btUpdate_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=localhost;Initial Catalog=student;Integrated Security=True";//连接数据库字符串
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
mandType = CommandType.Text;
mandText = "update users set erName='小王'where erid ='2'";
int rt = cmd.ExecuteNonQuery();
if (rt > 0)
{
Response.Write("<script language = 'javascript'>alert('修改成功!') ");
//Response.Write("修改成功!");
}
}。

相关主题