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[].ToString();
stu.Name = reader[].ToString();
stu.Major = reader[].ToString();
stu.Birthday = reader[].ToString();
stu.Sex = (reader[].ToString())==""?"男":"女"; 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>)
{
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[].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 > )
MessageBox.Show("重置成功。密码:123456");
else return;
}
05-11 14:04