連接數據庫, 請根據用用戶的輸入和數據庫里的信息進行比較, 判斷用戶名和密碼是否正確
數據庫設計:
數據庫名: MyDataBase1.mdf
表名: T_Users
表數據:
程序代碼
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Data.SqlClient;
- namespace 登錄
- {
- class Program
- {
- static void Main(string[] args)
- {
- //下面這段文字的作用已經在其它博文中解釋!
- string dataDir = AppDomain.CurrentDomain.BaseDirectory;
- if (dataDir.EndsWith(@"\bin\Debug\")
- || dataDir.EndsWith(@"\bin\Release\"))
- {
- dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
- AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
- }
- //定義用戶名和密碼變量
- string username, password;
- //提示用戶輸入用戶名和密碼
- Console.WriteLine("請輸入用戶名:");
- username = Console.ReadLine();
- Console.WriteLine("請輸入密碼:");
- password = Console.ReadLine();
- //使用創建數據庫連接
- using(SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDataBase1.mdf;Integrated Security=True;User Instance=True"))
- {
- conn.Open();//打開數據庫
- //創建數據庫查詢命令
- using(SqlCommand cmd = conn.CreateCommand())
- {
- //查詢命令為:查詢UserName等於輸入的用戶名
- cmd.CommandText = "select * from T_Users where UserName='" + username + "'";
- //將查詢到的數據保存在reader這個變量里
- using(SqlDataReader reader = cmd.ExecuteReader())
- {
- //如果reader.Read()的結果不為空, 則說明輸入的用戶名存在
- if(reader.Read())
- {
- /*從數據庫里查詢出和用戶相對應的PassWorld的值
- *reader.GetOrdinal("PassWord")的作用是得到PassWord的為這行數據中的第幾列,返回回值是int
- *reader.GetString()的作用是得到第幾列的值,返回類型為String.
- */
- string dbpassword = reader.GetString(reader.GetOrdinal("PassWord"));
- //比較用戶輸入的密碼與從數據庫中查詢到的密碼是否一至
- if(password==dbpassword)
- {
- //如果相等,就登錄成功
- Console.WriteLine("登錄成功!");
- }
- else
- {
- //如果不相等,說明密碼不對
- Console.WriteLine("輸入的密碼有誤!");
- }
- }
- else
- {
- //說明輸入的用戶名不存在
- Console.WriteLine("輸入的用戶名不存在!");
- }
- }
- }
- }
- Console.ReadKey();
- }
- }
- }