查询
/// <summary> /// 查询 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { string YiGuo = "server=.;database=YiGuo;uid=sa;pwd=sasa"; SqlConnection MyConnerction = new SqlConnection(YiGuo);//定义一个数据库连接 SqlCommand MyCommand = new SqlCommand("select * from Users", MyConnerction);//定义一个数据库戏迷指令 SqlDataAdapter SelectAdapter = new SqlDataAdapter();//定义一个数据适配器; SelectAdapter.SelectCommand = MyCommand;//定义数据适配器的操作指令 DataSet MyDataset = new DataSet();//定义一个数据集 MyConnerction.Open();//打开数据库连接; SelectAdapter.SelectCommand.ExecuteNonQuery();//执行数据库查询指令 MyConnerction.Close();//关闭数据库 SelectAdapter.Fill(MyDataset);//填充数据集 DataGrid1.DataSource = MyDataset.Tables[0]; ////DataGrid1.DataBind();//将数据表格用数据集中的数据填充 }
添加
/// <summary> /// 添加 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DataGrid1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void button2_Click(object sender, EventArgs e) { string YiGuo = "server=.;database=YiGuo;uid=sa;pwd=sasa"; SqlConnection MyConnerction = new SqlConnection(YiGuo); string MyInsert = ("insert into Users (6583,15565628888,www.j&q@com,女,9420)values('" + Convert.ToString(textBox1.Text) + "','" + Convert.ToString(textBox2.Text) + "','" + Convert.ToString(textBox3.Text) + "','" + Convert.ToString(textBox4.Text) + "','" + Convert.ToString(textBox5.Text) + "')"); SqlCommand MyCommand = new SqlCommand(MyInsert, MyConnerction); try//处理异常 { MyConnerction.Open(); MyCommand.ExecuteNonQuery(); MyConnerction.Close(); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
修改更新
/// <summary> /// 修改更新 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { string YiGuo = "server = .;database=YiGuo;uid=sa;pwd=sasa"; SqlConnection MyConnerction = new SqlConnection(YiGuo); string MyUpdata = "Update Users set 操作员 ='" + textBox2.Text + "'" + "where userName = " + "'" + textBox6.Text + "'"; SqlCommand MyCommand = new SqlCommand(MyUpdata, MyConnerction); try { MyConnerction.Open(); MyCommand.ExecuteNonQuery(); MyConnerction.Close(); textBox6.Text = ""; } catch(Exception ex) { MessageBox.Show(ex.Message); } }
删除
/// <summary> /// 删除 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button4_Click(object sender, EventArgs e) { string YiGuo = "server = .;database = YiGuo;uid = sa; pwd=sasa"; SqlConnection MyConnection = new SqlConnection(YiGuo); string MyData ="Delete from Users where UserID = "+ textBox5.Text; SqlCommand MyCommand = new SqlCommand(MyData,MyConnection); try { MyConnection.Open(); MyCommand.ExecuteNonQuery(); MyConnection.Close(); textBox6.Text = ""; } catch(Exception ex) { MessageBox.Show(ex.Message); } }