用VS2010+SQL2008做一个登录程序

 1 Console.WriteLine("请输入用户名");
 2             string username = Console.ReadLine();
 3             Console.WriteLine("请输入密码");
 4             string pwd = Console.ReadLine();
 5             using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\VS2010\Test\ADO\Database1.mdf;
 6 Integrated Security=True;User Instance=True")) //所有ADO.NET接口资源都实现了IDisposable接口,可以试用using 进行资源管理
 7             {
 8                 conn.Open();
 9                 //通过CMD命令执行插入表
10                 using (SqlCommand cmd = conn.CreateCommand())
11                 {   //先到表中查用户输入的用户名对应的信息 
12                     cmd.CommandText = "select * from T_Users where UserName='" + username + "'";
13                     using (SqlDataReader reader = cmd.ExecuteReader())
14                     {
15                         if (reader.Read())
16                         {
17                             //用户名存在
18                             string abpassword = reader.GetString(reader.GetOrdinal("password"));
19                             if (pwd == abpassword)//比较数据库中的密码是否在一致
20                             {
21                                 Console.WriteLine("登录成功");
22                             }
23                             else
24                             {
25                                 Console.WriteLine("密码错误,登录失败");
26                             }
27                         } 
28                         else//Read返回false,就是没有查找这个用户名
29                         {
30                             Console.WriteLine("用户名错误");
31                         }
32                     }
33                 }
34             }
35             Console.WriteLine("OK");
36             Console.ReadKey();
37         }

//附注:在写这个程序时,请先把本机上的SQL环境搭建好,SQL本机服务需开启

posted @ 2013-08-20 21:09  -112  阅读(529)  评论(0编辑  收藏  举报