VS2008C#Sqlserver2008数据库的连接以及增删改查

连接数据库

using System.Data.SqlClient;

SqlConnection conn;
//连接数据库
private void Form1_Load(object sender, EventArgs e)
{
    string constr = "server=ACER-PC\\LI;database=db_test;uid=sa;pwd=123";
    conn = new SqlConnection(constr);  //数据库连接   

}

查询

//这里只要连接数据库即可,不必打开数据库
private void button1_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("select * from tb_ls", conn);
 
    SqlDataAdapter sda = new SqlDataAdapter();
    sda.SelectCommand = cmd;
 
    DataSet ds = new DataSet();
 
    sda.Fill(ds, "cs");
 
    dataGridView1.DataSource = ds.Tables[0];

}

删除

private void button2_Click(object sender, EventArgs e)
{
    if (this.dataGridView1.SelectedRows.Count > 0)
    {
        DataRowView drv = dataGridView1.SelectedRows[0].DataBoundItem as DataRowView;
        drv.Delete();
    }
    conn.Open();//打开数据库
    SqlCommand cmd = new SqlCommand("delete from tb_ls where 编号="+this.dataGridView1.CurrentRow.Cells["编号"].Value+"",conn);
    cmd.ExecuteNonQuery();
    conn.Close();//关闭数据库
}

添加

private void button3_Click(object sender, EventArgs e)
{
    conn.Open();
    SqlCommand cmd = new SqlCommand("insert into tb_ls values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"')",conn);
    cmd.ExecuteNonQuery();
    conn.Close();
}

更新

private void button4_Click(object sender, EventArgs e)
{
    conn.Open();
    SqlCommand cmd = new SqlCommand("update tb_ls set 姓名='"+textBox2.Text+"',性别='"+textBox3.Text+"',年龄='"+textBox4.Text+"' where 编号='"+textBox1.Text+"'",conn);
    textBox1.ReadOnly = false;
    cmd.ExecuteNonQuery();
    conn.Close();
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值