windows窗体程序中的数据库操作部分 //数据库连接串internal static string connstring = Data Source = 192.168.1.1; Initial Catalog = testdb; User ID = test; pwd = 111111;; //学生登录using (Sq...
windows窗体程序中的数据库操作部分
//数据库连接串 internal static string connstring = "Data Source = 192.168.1.1; Initial Catalog = testdb; User ID = test; pwd = 111111;";
//学生登录 using (SqlConnection conn = new SqlConnection(login_mainform.connstring)) { string sql = "select * from test_student where name=@name and pwd=@pwd"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.Add(new SqlParameter("@name", txtusername.Text)); cmd.Parameters.Add(new SqlParameter("@pwd", txtpassword.Text)); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); Student stu = new Student(); if (reader.Read()) { stu.Sno = reader[0].ToString(); stu.Name = reader[1].ToString(); stu.Major = reader[2].ToString(); stu.Birthday = reader[3].ToString(); stu.Sex = (reader[4].ToString())=="1"?"男":"女"; Information info = new Information(stu); //新窗口对象 info.Show(); //显示学生信息 this.Hide(); //隐藏当前窗口 } else { MessageBox.Show("输入有误"); } #endregion }
//修改数据 using (SqlConnection conn = new SqlConnection(login_mainform.connstring)) { string sql = "update test_student set pwd=@pwd where sno=@sno"; SqlCommand cmd = new SqlCommand(sql,conn); cmd.Parameters.Add(new SqlParameter("@pwd", txtnewpwd.Text)); cmd.Parameters.Add(new SqlParameter("@sno", txtsno.Text)); conn.Open(); int rows= cmd.ExecuteNonQuery(); if (rows>0) { MessageBox.Show("密码修改成功,请重新登录"); login_mainform form = new login_mainform(); //登录窗口 form.Show(); this.Close(); } else MessageBox.Show("存储出错"); }
//连接数据库查询符合查询条件的数据 adapter using (SqlConnection conn = new SqlConnection(login_mainform.connstring)) { conn.Open(); String sql =String.Format("select sno,name,sex,birthday,major from test_student where name like '%{0}%' and major like '%{1}%' and sno like '%{2}%'", txtnamequery.Text,cmbmajor.Text,txtsnoquery.Text); SqlDataAdapter da = new SqlDataAdapter(sql,conn); DataSet ds = new DataSet(); da.Fill(ds); }
//更新密码 using (SqlConnection conn = new SqlConnection(login_mainform.connstring)) { conn.Open(); string sno = dgvstudent.CurrentRow.Cells[0].Value.ToString(); String sql = String.Format("update test_student set pwd = '123456' where sno = {0}", sno); SqlCommand cmd = new SqlCommand(sql, conn); int rows = cmd.ExecuteNonQuery(); if (rows > 0) MessageBox.Show("重置成功。密码:123456"); else return; }
沃梦达教程
本文标题为:数据库操作(c#)
基础教程推荐
猜你喜欢
- 在unity脚本中控制Inspector面板的参数操作 2023-04-14
- .NET Core 编写的 Windows 远程桌面记录清理工具 2023-09-27
- WPF 在image控件用鼠标拖拽出矩形的实现方法 2022-12-31
- Unity中协程IEnumerator的使用方法介绍详解 2023-06-14
- 解决unity3d导入模型贴图材质丢失的问题 2023-04-14
- c# – 如何以编程方式从实体获取具有模式名称的数据库表名 2023-11-24
- C#11新特性使用案例详解 2023-06-08
- C#实现平衡查找树 2023-05-31
- C#的this关键字的2种用法 2023-05-06
- C# 关于爬取网站数据遇到csrf-token的分析与解决 2023-03-29