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 }