【C#.NET】Winform-SQL数据库增删改查
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
//1-编写连接字符串(SQL用户名密码)
string conStr = "server=PC119\\SQLEXPRESS;database=Operator;uid=sa;pwd=12345678";
//2-创建连接对象,打开连接
SqlConnection conn = new SqlConnection(conStr); //创建连接对象
conn.Open(); //打开数据库连接
//3-编写SQL语句命令,增删改查。向sql中插入数据
string sql = string.Format("insert INTO Table1(用户名,密码,备注) VALUES('{0}','{1}','{2}')", this.txtUser.Text, this.txtPwd.Text, this.txtNode.Text);
//4-执行非查询SQL语句
SqlCommand cmd = new SqlCommand(sql, conn);
int rowCount = cmd.executeNonQuery(); //执行SQL语句,并返回受影响的行数
//5-关闭连接
conn.Close();
if (rowCount == 1)
{
MessageBox.Show("添加成功");
}
else
{
MessageBox.Show("添加失败");
}
ReadData(); //调用读取数据的方法,刷新数据int memId =int.Parse( GVTable.selectedRows[0].Cells[0].Value.ToString()); //获取选中行的第一列中的编号
string conStr = "server=PC119\\SQLEXPRESS;database=Operator;uid=sa;pwd=12345678";
SqlConnection conn = new SqlConnection(conStr); //创建连接对象
conn.Open(); //打开数据库连接
string sql = "delete from Table1 where 编号="+memId;
SqlCommand cmd= new SqlCommand(sql, conn);//执行哪条语句
int rowCount=cmd.executeNonQuery();//执行语句命令,并返回受影响的条数
conn.Close() ;//关闭数据库
if (rowCount==1)
{
MessageBox.Show("删除成功");
}
else
{
MessageBox.Show("删除失败");
}
ReadData();int memId = int.Parse(GVTable.selectedRows[0].Cells[0].Value.ToString()); //获取选中行的第一列中的编号
string conStr = "server=PC119\\SQLEXPRESS;database=Operator;uid=sa;pwd=12345678";
SqlConnection conn = new SqlConnection(conStr); //创建连接对象
conn.Open(); //打开数据库连接
string sql = "select * from Table1 where 编号=" + memId;//查询指令
SqlDataAdapter adp = new SqlDataAdapter(sql, conn); //查询
DataTable dt = new DataTable();
adp.Fill(dt); // 填充到DataTable
if (dt.Rows.Count == 0) //判断选中的行是否存在
{
MessageBox.Show("找不到信息");
return;
}
//选中行中的信息添加到文本当中。
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()); //获取选中行的第一列中的编号
string conStr = "server=PC119\\SQLEXPRESS;database=Operator;uid=sa;pwd=12345678";
SqlConnection conn = new SqlConnection(conStr); //创建连接对象
conn.Open(); //打开数据库连接
string sql = string.Format("update Table1 set 用户名='{0}',密码='{1}',备注='{2}' where 编号='{3}'",txtUser.Text,txtPwd.Text,txtNode.Text,memId);
SqlCommand cmd = new SqlCommand(sql, conn);
int rowCount = cmd.executeNonQuery();
//5-关闭连接
conn.Close();
if (rowCount == 1)
{
MessageBox.Show("修改成功");
}
else
{
MessageBox.Show("修改失败");
}
ReadData();该文章在 2023/5/17 12:26:01 编辑过 |
关键字查询
相关文章
正在查询... |