愤斗的程序猿丷
Keep on going never give up.
 1 /*通过C#winform程序访问数据库数据
 2 
 3 用到的命名空间和变量类型:
 4 
 5 using System.Data.SqlClient;
 6 
 7 SqlConnection;数据库连接类
 8 
 9 SqlCommand;数据库操作类
10 
11 SqlDataReader:读取 */
12 
13 //登录按钮代码
14 private void button1_Click(object sender, EventArgs e) 
15 {
16 if (textBox1.Text == "")
17 MessageBox.Show("用户名不能为空!", "提示");
18 else if (textBox2.Text == "")
19 MessageBox.Show("密码不能为空!", "提示");
20 try //try...catch...异常处理语句
21 {
22 string name, pass;
23 bool flag = false;
24 name = textBox1.Text;
25 pass = textBox2.Text; //获取用户名,密码
26 string str = "Data Source=SQL服务器名称;Initial Catalog=数据库名;User ID=登录名;Password=密码;";
27 SqlConnection myConn = new SqlConnection(str);//创建数据库连接类的对象
28 myConn.Open(); //将连接打开
29 //SQL语句:从数据库的登录表中搜索登录名,密码
30 string sqlstring = "select username,password from users where username='" +name + "'and password='" + pass + "'"; 
31 //执行con对象的函数,返回一个SqlCommand类型的对象
32 SqlCommand command = new SqlCommand(sqlstring, myConn);
33 //用cmd的函数执行语句,返回SqlDataReader对象thisReader,thisReader就是返回的结果集(也就是数据库中查询到的表数据)
34 SqlDataReader thisReader = command.ExecuteReader();
35 //判断用户名及密码是否正确,对flag进行赋值
36 while (thisReader.Read()) 
37 {
38 if ((thisReader.GetValue(0).ToString().Trim()) == (name.ToString().Trim()))
39 {
40 if (thisReader.GetValue(1).ToString().Trim() == pass.ToString().Trim())
41 {
42 flag = true;
43 }
44 }
45 }
46 //用完后关闭连接,以免影响其他程序访问
47 myConn.Close(); 
48 if (flag)
49 {
50 MessageBox.Show("登陆成功!");
51 Form2 F = new Form2(); //显示主页面
52 F.Show();
53 this.Hide();
54 }
55 else
56 {
57 MessageBox.Show("请检查你的用户名和密码!");
58 textBox1.Focus();
59 }
60 }
61 catch (Exception ex2)
62 {
63 MessageBox.Show("连接远程SQL数据库发生错误:" + ex2.ToString(), "错误!");
64 }

 

posted on 2016-07-09 14:51  愤斗的程序猿丷  阅读(23267)  评论(0编辑  收藏  举报