1 package jdbcDome; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.util.Scanner; 8 9 import javafx.geometry.Side; 10 11 12 13 /** 14 * 15 * @author 不凡 16 *這裏是使用的基礎的方法,也是一開始學習的方法, 17 * 可是不能防止SQL注入,(可是能夠在輸入框中限制特殊字符輸入來達到一樣的目的) 18 * 下面的是預編譯語句對象 19 */ 20 public class DBText { 21 public static void main(String[] args) { 22 /* 23 24 * 25 * 26 jdbcTools db1 =jdbcTools.getDB(); 27 Scanner sc1 =new Scanner(System.in); 28 System.out.println("請輸入你的帳號: "); 29 int Sid = sc1.nextInt(); 30 System.out.println("請輸入你的密碼"); 31 String pwd = sc1.next(); 32 String sqlQuery="select * from student where sid = "+Sid+" and pwd ='"+pwd+"'"; 33 34 ResultSet rs1 = db1.query(sqlQuery); 35 try { 36 if(rs1.next()) 37 { 38 System.out.println("登錄成功!"); 39 System.out.println(sqlQuery); 40 System.out.println(rs1.getString(2)); 41 }else { 42 System.out.println("登錄失敗!"); 43 44 } 45 46 } catch (SQLException e) { 47 // TODO Auto-generated catch block 48 e.printStackTrace(); 49 } 50 51 */ 52 //-------------------------------------------------------------------------------------------- 53 //這裏使用的預編譯語句對象 有三個特色 54 /* 1.防止SQL注入 55 * 2.簡單 56 * 3.能夠用(?)問號,充當佔位 更加方便 57 * 4.語句只編譯執行效率更高。 58 * 59 */ 60 Scanner sc1 =new Scanner(System.in); 61 System.out.println("請輸入你的帳號: "); 62 int Sid = sc1.nextInt(); 63 System.out.println("請輸入你的密碼"); 64 String pwd = sc1.next(); 65 // 問好(?) 表示佔位符 66 String sqlQuery="select * from student where sid = ? and pwd =?"; 67 Connection con1 = jdbcTools.getConn(); 68 try { 69 //生成預編譯語句對象 70 PreparedStatement pSt = con1.prepareStatement(sqlQuery); 71 //給佔位符賦值 72 pSt.setInt(1, Sid); 73 pSt.setString(2, pwd); 74 //執行預編譯對象 75 ResultSet rs2= pSt.executeQuery(); 76 if(rs2.next()){ 77 System.out.println("登錄成功"); 78 rs2.getString(2); 79 }else{ 80 System.out.println("登錄失敗!"); 81 } 82 83 } catch (SQLException e) { 84 e.printStackTrace(); 85 } 86 87 } 88 89 }