1 package org.west.demo4; 2 3 import java.sql.*; 4 5 public class Test { 6 public static void main(String[] args) { 7 Connection connection=null; 8 PreparedStatement ps=null; 9 ResultSet resultSet=null; 10 try { 11 //加載類驅動 12 Class.forName("com.mysql.jdbc.Driver"); 13 //建立連接 14 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcstudy", "root", "123456"); 15 16 String sql="select id,Sname,pwd from t_user where id>?"; 17 //通過connection 獲取prepareStatement對象對sql語句進行預編譯 防止sql注入 18 ps = connection.prepareStatement(sql); 19 //paramenterindex:1 表示第一個占位符所需要輸入的數值 20 ps.setString(1,"2"); 21 //executeQuery()執行查找元素返回的結果集 22 resultSet = ps.executeQuery(); 23 while(resultSet.next()){ 24 //columnindex 表示的是數據庫的第一列的需要查詢的那個列的屬性的信息 比如 id 25 System.out.println(resultSet.getString(1)); 26 //Sname 27 System.out.println(resultSet.getString(2)); 28 //pwd 29 System.out.println(resultSet.getString(3)); 30 } 31 32 } catch (ClassNotFoundException e) { 33 e.printStackTrace(); 34 } 35 catch (SQLException e) { 36 e.printStackTrace(); 37 }finally{ 38 if(connection!=null){ 39 try { 40 connection.close(); 41 } catch (SQLException e) { 42 e.printStackTrace(); 43 } 44 } 45 if(ps!=null){ 46 try { 47 ps.close(); 48 } catch (SQLException e) { 49 e.printStackTrace(); 50 } 51 } 52 if(resultSet!=null){ 53 try { 54 resultSet.close(); 55 } catch (SQLException e) { 56 e.printStackTrace(); 57 } 58 } 59 60 } 61 } 62 }