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();
}

 

posted @   路边有一棵草  阅读(11980)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示