1. 程式人生 > 其它 >③新建user表,插入資料,編寫登入程式測試

③新建user表,插入資料,編寫登入程式測試

使用者表:使用者id,姓名,密碼,部門,職位

建表以及插入資料的sql語句

CREATE TABLE User          
          (Uid   CHAR(8) PRIMARY KEY, /* 列級完整性約束條件*/                  
            Uname  CHAR(20) UNIQUE,     /* Sname取唯一值*/
            Upwd    CHAR(40),
            Udpt   CHAR(20),
            UM  CHAR(20)
           );

INSERT  INTO  User    VALUES (
'12345601','張成民','123456789','部門一','科員'); INSERT INTO User VALUES ('12345602','張民','12345678','部門一','科員');

對登入行為進行使用者名稱與密碼的匹配,即在資料庫中查詢id+密碼,判斷資料庫返回是否有一行,若返回行數不為一則判斷密碼錯誤,需要跳轉重新輸入

若密碼正確則登入成功並列印輸出個人資訊

程式碼實現login函式如下

int login()
{

    MYSQL* my = mysql_init(NULL);

    if (!mysql_real_connect(my, "
122.112.198.128", "rui1220", "z159753Z", "rui1220", 3306, NULL, 0)) { printf("connect error !\n"); mysql_close(my); } mysql_query(my, "SET NAMES 'GB2312' "); char Uid[100]; char pw[100]; char str2[100] = "select * from User where Uid='12345601';"; char sql[100]; sign: printf(
"請輸入使用者名稱\n"); scanf_s("%s", &Uid,10); printf("請輸入密碼\n"); scanf_s("%s", &pw, 10); sprintf_s(sql, "select * from User where Uid='%s' and Upwd='%s';", Uid,pw); //printf("%s\n", sql); int res = mysql_query(my, sql); //printf("%d", res); MYSQL_RES* a = mysql_store_result(my); int rows = mysql_num_rows(a);//行數量 int cols = mysql_num_fields(a);//列數量 //printf("%d\n", rows); if (!rows) { printf("使用者名稱或密碼錯誤,請重新輸入\n"); goto sign; } printf("登陸成功\n"); //列印個人資訊 MYSQL_ROW line; line = mysql_fetch_row(a); printf("歡迎使用公文傳輸系統\n"); printf("姓名:%s\n", line[1]); printf("工號:%s\n", line[0]); printf("部門:%s\n", line[3]); printf("職位:%s\n", line[4]); mysql_close(my); return 0; }