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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM