VS2008 C# Sql server2008 数据库的连接,增删改查

 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();}//将选中的某一行的信息显示在TextBox文本框中private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e){textBox1.ReadOnly = true;textBox1.Text = this.dataGridView1.CurrentRow.Cells["编号"].Value.ToString();textBox2.Text = this.dataGridView1.CurrentRow.Cells["姓名"].Value.ToString();textBox3.Text = this.dataGridView1.CurrentRow.Cells["性别"].Value.ToString();textBox4.Text = this.dataGridView1.CurrentRow.Cells["年龄"].Value.ToString();}

,放下一处烦恼,收获一个惊喜;放下一种偏见,收获一种幸福;

VS2008 C# Sql server2008 数据库的连接,增删改查

相关文章:

你感兴趣的文章:

标签云: