最近剛剛開始學習mysql,所以就寫了這個很基本的用戶注冊登錄的功能來練練手。雖然這個很簡單,但是我還是看到了自己學習的進步,很開心。哈哈哈。
這里要注意數據表的建立:

直接上代碼吧,里面注釋很詳細了。
package client;import java.sql.*;import java.util.*;public class Client { /** * 用以實現用戶的注冊和登錄 */ private static String username;//用戶登錄注冊的姓名 private static String password;//用戶密碼 private static String url="jdbc:mysql://localhost:3306/test";//連接數據庫的url,test是我自己的一個數據庫啊寶寶們。 private static String user="root";//mysql登錄名 private static String pass="123456";//mysql登錄密碼(寫自己之前設置的) private static Connection con;// static Scanner input =new Scanner(System.in); public static void main(String[] args) throws Exception { //加載數據庫連接驅動并連接 Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection(url,user,pass); System.out.println("********用戶界面********"); System.out.println("請選擇:/n 1:用戶登錄/n 2:用戶注冊"); System.out.println("**********************"); int i=input.nextInt(); switch(i){ case 1: denglu(); break; case 2: zhuce(); break; default : System.out.println("輸入有誤!"); System.exit(0); } } //用戶注冊 public static void zhuce() throws SQLException{ System.out.println("請輸入你的姓名:"); username=input.next(); System.out.println("請輸入你的登錄密碼:"); String p1=input.next(); System.out.println("請再次輸入你的確認密碼:"); String p2=input.next(); if(p1.equals(p2)){ //兩次輸入的密碼相同才可以注冊 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("注冊成功!/n請登錄:"); denglu(); }else{ System.out.println("你輸入的密碼與確認密碼不相符,請重新注冊:"); zhuce(); } } //用戶登錄 public static void denglu() throws SQLException{ System.out.println("請輸入你的姓名:"); username=input.next(); System.out.println("請輸入你的密碼:"); 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(); //從登錄用戶給出的賬號密碼來檢測查詢在數據庫表中是否存在相同的賬號密碼 if(rs.next()){ System.out.println("登錄成功!"); }else{ System.out.println("姓名或密碼錯誤!/n請重新登錄:"); denglu(); } }}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答