【C#.NET】Winform-SQL數(shù)據(jù)庫(kù)增刪改查
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
//1-編寫(xiě)連接字符串(SQL用戶名密碼) string conStr = "server=PC119\\SQLEXPRESS;database=Operator;uid=sa;pwd=12345678"; //2-創(chuàng)建連接對(duì)象,打開(kāi)連接 SqlConnection conn = new SqlConnection(conStr); //創(chuàng)建連接對(duì)象 conn.Open(); //打開(kāi)數(shù)據(jù)庫(kù)連接 //3-編寫(xiě)SQL語(yǔ)句命令,增刪改查。向sql中插入數(shù)據(jù) string sql = string.Format("insert INTO Table1(用戶名,密碼,備注) VALUES('{0}','{1}','{2}')", this.txtUser.Text, this.txtPwd.Text, this.txtNode.Text); //4-執(zhí)行非查詢SQL語(yǔ)句 SqlCommand cmd = new SqlCommand(sql, conn); int rowCount = cmd.executeNonQuery(); //執(zhí)行SQL語(yǔ)句,并返回受影響的行數(shù) //5-關(guān)閉連接 conn.Close(); if (rowCount == 1) { MessageBox.Show("添加成功"); } else { MessageBox.Show("添加失敗"); } ReadData(); //調(diào)用讀取數(shù)據(jù)的方法,刷新數(shù)據(jù) int memId =int.Parse( GVTable.selectedRows[0].Cells[0].Value.ToString()); //獲取選中行的第一列中的編號(hào) string conStr = "server=PC119\\SQLEXPRESS;database=Operator;uid=sa;pwd=12345678"; SqlConnection conn = new SqlConnection(conStr); //創(chuàng)建連接對(duì)象 conn.Open(); //打開(kāi)數(shù)據(jù)庫(kù)連接 string sql = "delete from Table1 where 編號(hào)="+memId; SqlCommand cmd= new SqlCommand(sql, conn);//執(zhí)行哪條語(yǔ)句 int rowCount=cmd.executeNonQuery();//執(zhí)行語(yǔ)句命令,并返回受影響的條數(shù) conn.Close() ;//關(guān)閉數(shù)據(jù)庫(kù) if (rowCount==1) { MessageBox.Show("刪除成功"); } else { MessageBox.Show("刪除失敗"); } ReadData(); int memId = int.Parse(GVTable.selectedRows[0].Cells[0].Value.ToString()); //獲取選中行的第一列中的編號(hào) string conStr = "server=PC119\\SQLEXPRESS;database=Operator;uid=sa;pwd=12345678"; SqlConnection conn = new SqlConnection(conStr); //創(chuàng)建連接對(duì)象 conn.Open(); //打開(kāi)數(shù)據(jù)庫(kù)連接 string sql = "select * from Table1 where 編號(hào)=" + memId;//查詢指令 SqlDataAdapter adp = new SqlDataAdapter(sql, conn); //查詢 DataTable dt = new DataTable(); adp.Fill(dt); // 填充到DataTable if (dt.Rows.Count == 0) //判斷選中的行是否存在 { MessageBox.Show("找不到信息"); return; } //選中行中的信息添加到文本當(dāng)中。 this.txtUser.Text = dt.Rows[0]["用戶名"].ToString(); this.txtPwd.Text = dt.Rows[0]["密碼"].ToString(); this.txtNode.Text = dt.Rows[0]["備注"].ToString(); conn.Close(); int memId = int.Parse(GVTable.selectedRows[0].Cells[0].Value.ToString()); //獲取選中行的第一列中的編號(hào) string conStr = "server=PC119\\SQLEXPRESS;database=Operator;uid=sa;pwd=12345678"; SqlConnection conn = new SqlConnection(conStr); //創(chuàng)建連接對(duì)象 conn.Open(); //打開(kāi)數(shù)據(jù)庫(kù)連接 string sql = string.Format("update Table1 set 用戶名='{0}',密碼='{1}',備注='{2}' where 編號(hào)='{3}'",txtUser.Text,txtPwd.Text,txtNode.Text,memId); SqlCommand cmd = new SqlCommand(sql, conn); int rowCount = cmd.executeNonQuery(); //5-關(guān)閉連接 conn.Close(); if (rowCount == 1) { MessageBox.Show("修改成功"); } else { MessageBox.Show("修改失敗"); } ReadData(); 該文章在 2023/5/17 12:26:01 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |