数据库连接代码
连接数据库:
命名空间:using System.Data.SqlClient;
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;
https://www.360docs.net/doc/4310093289.html,mandType = CommandType.Text;//配置类型
https://www.360docs.net/doc/4310093289.html,mandText = "select * from users";//sql语句
SqlDataReader sr = cmd.ExecuteReader();
while (sr.Read())
{
Response.Write( "
"+"userid:" + sr.GetInt32(0));
}
sr.NextResult();
while (sr.Read())
{
Response.Write("
" + "userName:" + sr.GetString(0));
}
sr.Close();
conn.Dispose();
conn.Close();
}
在原数据表中新增一条数据:
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;
https://www.360docs.net/doc/4310093289.html,mandType = CommandType.Text;
https://www.360docs.net/doc/4310093289.html,mandText = "insert into users values (4,'ddd')";
int rt = cmd.ExecuteNonQuery();
if (rt >= 0)
{
Response.Write("新增成功!");
}
}
在原有数据表中修改一条数据:
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;
https://www.360docs.net/doc/4310093289.html,mandType = CommandType.Text;
https://www.360docs.net/doc/4310093289.html,mandText = "update users set https://www.360docs.net/doc/4310093289.html,erName='小王'where https://www.360docs.net/doc/4310093289.html,erid ='2'";
int rt = cmd.ExecuteNonQuery();
if (rt > 0)
{
Response.Write("