数据库连接代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
连接数据库:
命名空间: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;
mandType = CommandType.Text;//配置类型
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;
mandType = CommandType.Text;
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;
mandType = CommandType.Text;
mandText = "update users set erName='小王'where erid ='2'";
int rt = cmd.ExecuteNonQuery();
if (rt > 0)
{
Response.Write("