最近剛剛開始學(xué)習(xí)mysql,所以就寫了這個(gè)很基本的用戶注冊(cè)登錄的功能來練練手。雖然這個(gè)很簡(jiǎn)單,但是我還是看到了自己學(xué)習(xí)的進(jìn)步,很開心。哈哈哈。
這里要注意數(shù)據(jù)表的建立:
直接上代碼吧,里面注釋很詳細(xì)了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
package client; import java.sql.*; import java.util.*; public class Client { /** * 用以實(shí)現(xiàn)用戶的注冊(cè)和登錄 */ private static String username; //用戶登錄注冊(cè)的姓名 private static String password; //用戶密碼 private static String url= "jdbc:mysql://localhost:3306/test" ;//連接數(shù)據(jù)庫的url,test是我自己的一個(gè)數(shù)據(jù)庫啊寶寶們。 private static String user= "root" ; //mysql登錄名 private static String pass= "123456" ; //mysql登錄密碼(寫自己之前設(shè)置的) private static Connection con; // static Scanner input = new Scanner(System.in); public static void main(String[] args) throws Exception { //加載數(shù)據(jù)庫連接驅(qū)動(dòng)并連接 Class.forName( "com.mysql.jdbc.Driver" ); con=DriverManager.getConnection(url,user,pass); System.out.println( "********用戶界面********" ); System.out.println( "請(qǐng)選擇:\n 1:用戶登錄\n 2:用戶注冊(cè)" ); System.out.println( "**********************" ); int i=input.nextInt(); switch (i){ case 1 : denglu(); break ; case 2 : zhuce(); break ; default : System.out.println( "輸入有誤!" ); System.exit( 0 ); } } //用戶注冊(cè) public static void zhuce() throws SQLException{ System.out.println( "請(qǐng)輸入你的姓名:" ); username=input.next(); System.out.println( "請(qǐng)輸入你的登錄密碼:" ); String p1=input.next(); System.out.println( "請(qǐng)?jiān)俅屋斎肽愕拇_認(rèn)密碼:" ); String p2=input.next(); if (p1.equals(p2)){ //兩次輸入的密碼相同才可以注冊(cè) password=p1; String sql= "insert into client (username,password) values(?,?)" ; PreparedStatement ptmt=con.prepareStatement(sql); ptmt.setString( 1 , username); ptmt.setString( 2 , password); ptmt.execute(); System.out.println( "注冊(cè)成功!\n請(qǐng)登錄:" ); denglu(); } else { System.out.println( "你輸入的密碼與確認(rèn)密碼不相符,請(qǐng)重新注冊(cè):" ); zhuce(); } } //用戶登錄 public static void denglu() throws SQLException{ System.out.println( "請(qǐng)輸入你的姓名:" ); username=input.next(); System.out.println( "請(qǐng)輸入你的密碼:" ); password=input.next(); String sql= "select username,password from client where username=? and password=?" ; PreparedStatement ptmt=con.prepareStatement(sql); ptmt.setString( 1 , username); ptmt.setString( 2 , password); ResultSet rs=ptmt.executeQuery(); //從登錄用戶給出的賬號(hào)密碼來檢測(cè)查詢?cè)跀?shù)據(jù)庫表中是否存在相同的賬號(hào)密碼 if (rs.next()){ System.out.println( "登錄成功!" ); } else { System.out.println( "姓名或密碼錯(cuò)誤!\n請(qǐng)重新登錄:" ); denglu(); } } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。