兩種方法:
一、直接拼接到SQL語句
public static void main(String[] args) throws Exception{ //輸入賬號密碼 Scanner sc = new Scanner(System.in); System.out.println("賬號:"); String zh = sc.next(); System.out.println("密碼:"); String mm = sc.next(); //連接到數據庫 zh = zh.replace('\'', '\"');//防止有注入錯誤 Class.forName("com.mysql.jdbc.Driver"); Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb","root",""); Statement sta = conn.createStatement(); String sql = "select * from xs where zhanghao='"+zh+"' and mima='"+mm+"'";//拼接進去但是會有注入錯誤 ResultSet rs = sta.executeQuery(sql); //查詢語句 //輸出 if(rs.next()){ //sr.next==true 賬號密碼輸入的符合時 System.out.println(rs.getString(3)+"登入成功"); } else{ //輸入的不符合時 System.out.println("賬號或者密碼輸入不正確"); } conn.close(); }
二、使用prepareStatement語句,輸入特殊符號不會有問題,可以防止有注入的問題
public static void main(String[] args) throws Exception { //輸入賬號密碼 Scanner sc = new Scanner(System.in); System.out.println("賬號:"); String zh = sc.next(); System.out.println("密碼:"); String mm = sc.next(); //數據庫查詢賬號密碼是否正確 Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb", "root", "");
String sql = "select * from xs where zhanghao=? and mima=?;"; PreparedStatement sta = conn.prepareStatement(sql);//直接用prepareStatement語句,sql語句可以寫在里面; sta.setString(1, zh);//第一個?的內容 sta.setString(2, mm);//第二個?的內容 ResultSet rs = sta.executeQuery();//查詢語句上面寫過sql語句,這里不能寫。 //輸出 if(rs.next()){ //sr.next==true 賬號密碼輸入的符合時 System.out.println(rs.getString(3)+"登入成功"); } else{ //輸入的不符合時 System.out.println("賬號或者密碼輸入不正確"); } conn.close(); }
最后的結果也都是一樣的
注冊
使用prepareStatement語句,往數據庫里添加。好處是不受特殊字符的影響。
public static void main2(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); System.out.println("賬號:"); String zh = sc.nextLine(); System.out.println("密碼:"); String mm = sc.nextLine(); System.out.println("名稱:"); String xm = sc.nextLine(); Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK","root","");
String sql = "insert into xs values(?,?,?)"; PreparedStatement pre = conn.prepareStatement(sql); pre.setString(1, zh); pre.setString(2, mm); pre.setString(3, xm); pre.executeUpdate(); conn.close(); }
執行:
添加進數據庫里了