码迷,mamicode.com
首页 > 数据库 > 详细

jdbc总结

时间:2017-12-02 23:16:02      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:bundle   获取   操作   ase   文件夹   cat   let   creates   dex   

转载于:http://ask.csdn.net/questions/274857?sort=votes_count

1. JDBC的简介

1.1 jdbc:Java DataBase Connectivity,Java数据库的连接

1.2 比如有一台电脑,想在电脑上安装显卡,需要显卡的驱动,由显卡生产厂商提供

1.3 要想使用java对数据库进行操作,需要使用由数据库提供的数据库驱动

1.4 一个程序,使用java操作数据库,掌握java代码,出了掌握java代码之外,需要掌握数据库驱动的代码。

但是我们有很多的数据库,比如mysql、oracle,对于程序员来说,需要掌握每种数据库的代码,对于程序员来说压力很大

1.5 sun公司针对这种情况,开发出一套标准接口,各个数据库只需要实现这个借口就可以了,程序员只需要掌握这套借口就可以了,这套标准的借口就是jdbc

1.6 如果想要使用jdbc对数据库进行操作,首先安装数据库的驱动,不同的数据库提供驱动使用jar的形式提供,需要把jar包房在项目里面,相当于安装了数据库的驱动

1.7 导入jar到项目中(使用开发者工具myeclipse10.x版本)

· 首先创建一个文件夹lib,把jar包复制到lib里面,选中jar包右键点击build path -- add to build path,

当jar包前面的图标变成一个“小奶品”图标,表示导入jar成功

2. JDBC的入门案例

2.1 使用jdbc对数据库进行操作步骤是固定的

2.1.1 使用到的类和接口

DriverManager

Connection

Statement

ResultSet

2.2 jdbc的操作步骤

(1)加载数据库的驱动

DriveManager里面的registerDriver(Driver driver)

(2)创建与数据库的连接

DriverManager里面getConnection(String url, String user, String password)

(3)编写sql语句

(4)执行sql语句

Statement里面executeQuery(String sql)

(5)释放资源(关闭连接)

2.3 使用jdbc实现查询的操作

2.3.1 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static void main(String[] args) throws Exception {
    //加载驱动
    DriverManager.registerDriver(new Driver());
    //创建连接
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb2", "root", "root");
    //编写sql
    String sql = "select * from user";
    //执行sql
    //得到statement
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    //遍历结果集得到每条记录
    while(rs.next()) {
        int id = rs.getInt("id");
        String username = rs.getString("username");
        int chinese = rs.getInt("chinese");
        int english = rs.getInt("english");
        System.out.println(id+" :: "+username+" :: "+chinese+" :: "+english);
    }
    //释放资源
    rs.close();
    stmt.close();
    conn.close();
}

 

 

3. jdbc的DriverManager对象

3.1 在java.sql包里面

3.2 加载数据库驱动

registerDriver(Driver driver):参数是数据库驱动,这个驱动是由数据库提供的

(1)这个方法在实际开发中,一般是不使用的,因为这个方法会加载驱动两次

在源代码中,加载了一次Driver

(2)一般在开发中使用反射的方式加载数据库的驱动

Class.forName("com.mysql.jdbc.driver");

3.3 得到数据库的连接

getConnection(Strring url, String user, String password),返回Connection

· 有三个参数:

(1)url:表示要连接的数据库

写法:jdbc:mysql://数据库的ip:数据库的端口号/连接的数据库的名称

示例:jdbc:mysql://localhost:3306/testdb1

简写的方式:jdbc:mysql:///testdb1(使用范围:连接的数据库是本机,端口是3306)

(2)表示连接数据库的用户名

(3)表示连接数据库的用户密码

4. jdbc的Connection对象

4.1 代表数据库的连接,是接口,在java.sql包里面

4,.2 创建Statement对象:Statement createStatement()

4.3 创建预编译对象PreparedStatement prepareStatement(String sql)

5. jdbc的Statement对象

5.1 执行sql的对象,接口,在java.sql包里面

5.2 执行查询操作方法

ResultSet executeQuery(String sql) , 返回查询的结果集

5.3 执行增加 修改 删除的方法

int executeUpdate(String sql),返回成功的记录数

5.4 执行sql语句的方法

boolean execute(String sql),返回是布尔类型,如果执行的是查询的操作返回true,否则返回false

5.5 执行批处理的方法

addBatch(String sql) :把多个sql语句放到批处理里面

int[] executeBatch() :执行批处理里面的所有的sql

6. jdbc的ResultSet对象

6.1 代表查询之后返回的结果,借口,在java.sql包里面类似于使用select语句查询出来的表格

6.2 遍历结果集 next()

6.3 得到数据的具体指

· 如果是String类型,使用getString("字段的名称");

· 如果是int类型,使用getInt("字段的名称");

· 如果是不知道的类型,使用getObject("字段的名称");

6.4 结果集的遍历方式

· 在最开始的时候,指向第一行之前,当执行了next方法之后,一行一行的向下进行遍历,在默认的情况下,只能向下,不能向上。遍历出来的结果也是不能修改的

7. jdbc的释放资源

7.1 关闭的原则:谁最先打开,谁最后关闭

7.2 关闭资源的规范的写法

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
finally {
    //释放资源
    if(rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        rs = null;
    }
     
    if(stat != null) {
        try {
            stat.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        stat = null;
    }
     
    if(conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        conn = null;
    }          
}

 

8. 使用jdbc进行crud操作:代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class TestJDBC1 {
 
    /**
     * 使用jdbc完成数据库的查询和增加的操作
     * @param args
     */
    public static void main(String[] args) {
//      addUser(); //添加
//      selectUser();//查询
//      updateUser();//修改
        dropUser();//删除
    }
    public static void addUser() {
        Connection conn = null;
        Statement stat = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb1", "root", "root");
             
            String sql = "insert into user values(null,‘sunquan‘,‘123‘)";
             
            stat = conn.createStatement();
            stat.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(stat!=null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                stat = null;
            }
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                conn = null;
            }
        }
    }
 
    //查询user表里,name=liubei的人的
    public static void selectUser() {
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //创建连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb1", "root", "root");
            //写sql语句
            String sql = "select * from user where name=‘liubei‘";
            //执行sql
            stat = conn.createStatement();
            rs = stat.executeQuery(sql);
            while(rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String password = rs.getString("password");
                 
                System.out.println(id+" "+name+" "+password);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
             
            //关闭资源
            if(rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                rs = null;
            }
            if(stat!=null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                stat = null;
            }
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                conn=null;
            }
        }
         
    }
     
    //用jdbc实现删除操作
    //把id=5的小伙伴删了
    public static void dropUser() {
        Connection conn = null;
        Statement stat = null;
        try {
            //加载驱动,创建连接
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb1","root","root");
             
            //编写sql语句,执行sql
            String sql = "delete from user where id=5";
            stat = conn.createStatement();
            stat.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(stat!=null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                stat = null;
            }
             
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                conn = null;
            }
        }
    }
     
    //用jdbc实现修改操作
    //把id=5的,name=caocao,password=321
    public static void updateUser() {
        Connection conn = null;
        Statement stat = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb1","root","root");
             
            String sql = "update user set name=‘caocao‘,password=‘321‘ where id=5";
             
            stat = conn.createStatement();
            stat.executeUpdate(sql);
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(stat!=null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                stat = null;
            }
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                conn = null;
            }
        }
    }
}


8. jdbc工具类的封装

 

8.1 当在很多的类里面有相同的代码,可以把相同的代码提取到一个类里面,在类里面直接调用工具类里面的方法实现

8.2 在jdbc实现crud操作的代码里面,首先得到数据库连接,和释放资源的代码是重复的,所以可以进行封装

8.3 可以把数据库的一些信息,写到配置文件里面,在工具类读取配置文件得到内容

一般使用properties格式文件作为存储数据库信息的文件。

· properties文件示例:

drivername=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/testdb1

有两种方式读取配置文件:

(1)使用properties类:代码示例:

 

1
2
3
4
5
6
7
8
9
10
//创建properties对象
Properties p = new Properties();
//文件的输入流
InputStream in = new FileInputStream("src/db.properties");
//把文件的输入流放到对象里面
p.load(in);
String drivername = p.getProperty("drivername");
String url = p.getProperty("url");
String username = p.getProperty("username");
String password = p.getProperty("password");

(2)使用ResourceBundle类

 

· 使用范围:首先读取的文件格式需要时properties,文件需要放到src目录下

· 代码示例:

 

1
2
3
4
String drivername = ResourceBundle.getBundle("db").getString("drivername");
String url = ResourceBundle.getBundle("db").getString("url");
String username = ResourceBundle.getBundle("db").getString("username");
String password = ResourceBundle.getBundle("db").getString("password");

 

8.4 综上所述,将加载驱动,获取连接,关闭资源的代码封装起来

· 代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
 
public class JdbcUtils {
     
    public static String driver;
    public static String url;
    public static String name;
    public static String pass;
     
    //读取properties配置文件
    static {
        //ResouceBundle局限性,需要文件的后缀是properties且放在src目录下
        ResourceBundle rb = ResourceBundle.getBundle("db");
        driver = rb.getString("driver");
        url = rb.getString("url");
        name = rb.getString("username");
        pass = rb.getString("password");
    }
     
    //加载驱动,创建连接
    public static Connection getConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day05", "root", "root");
        return conn;
    }
     
    //关闭资源
    public static void closeConnection(Connection conn, Statement stat, ResultSet rs) {
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs=null;
        }
         
        if(stat!=null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            stat = null;
        }
         
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn = null;
        }
    }
}

 

9. sql的注入和防止

9.1 模拟登陆的效果

(1)登陆的实现步骤:

· 首先输入用户名和密码

· 第二,拿到输入的用户名和密码,到数据库里面进行查询,如果用户名和密码都正确,才表示登陆成功

· 但是如果用户名和密码,有一个是错误的,表示登录失败

9.2 演示sql的注入

· 在登陆的时候,用户名里面输入bbb,密码里面输入111 or ‘1=1‘。

这时在sql语句里面会是这样的:

select * from user where id=‘bbb‘ and password = ‘111‘ or ‘1=1‘;

这时会把用户输入的内容当做sql的查询条件,二不是作为整个用户名或者密码

9.3 防止sql的注入

(1)使用PreparedStatement预编译对象防止sql注入

(2)创建PreparedStatement对象preparedStatement(String sql)

(3)PreparedStatement借口的父接口:Statement
(4)什么是预编译?

参数在sql语句之后传入,会输入的项目作为一整个参数,而不是字符串拼接的形式

(5)步骤:

· 第一步:加载驱动,创建数据库连接

· 第二步,编写sql

· 第三步,需要对sql进行预编译

· 第四步,向sql里面设置参数

· 第五步,执行sql

· 第六步,释放资源

(6)代码示例

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//使用工具类得到数据库的连接
conn = JdbcUtils.getConnection();
//编写sql
String sql = "select * from user where username=? and password=?";
//对sql进行预编译
psmt = conn.prepareStatement(sql);
//设置参数
psmt.setString(1, username);
psmt.setString(2, password);
//执行sql
rs = psmt.executeQuery();
if(rs.next()) {
    System.out.println("login success");
} else {
    System.out.println("fail");
}

 

 

10. 完整代码示例:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
import utils.JdbcUtils;
 
/*
创建的表:
create table user(
id int primary key auto_increment,
username varchar(40),
password varchar(40)
);
insert into user values(null,‘zhaoyun‘,‘123‘);
insert into user values(null,‘caocao‘,‘123‘);
insert into user values(null,‘guanyu‘,‘123‘);
insert into user values(null,‘zhangfei‘,‘123‘);
insert into user values(null,‘liubei‘,‘123‘);
 */
public class Test {
 
    public static void main(String[] args) {
        selectUser(3);
//      addUser(0,"huangzhong","666");//0可以替代null
//      updateUser(9,"sunquan","234");
//      dropUser("huangzhong");
    }
     
    //预编译的方式查询数据
    //根据id的条件查询
    public static void selectUser(int id) {
        Connection conn = null;
        PreparedStatement pre = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = JdbcUtils.getConnection();
             
            String sql = "select * from user where id=?";
            //预编译sql语句
            pre = conn.prepareStatement(sql);
            pre.setInt(1, id);
             
            //执行sql语句
            rs = pre.executeQuery();
            while(rs.next()) {
                String username = rs.getString("username");
                String password = rs.getString("password");
                 
                System.out.println(id+" :: "+username+" :: "+password);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeConnection(conn, pre, rs);
        }
    }
     
    //预编译的方式添加
    //添加一个username=huangzhong,password=666的user
    public static void addUser(int id,String username,String password){
        Connection conn = null;
        PreparedStatement pre = null;
        try {
            //getConnection
            conn = JdbcUtils.getConnection();
            //sql
            String sql = "insert into user values(?,?,?)";
            //pre
            pre = conn.prepareStatement(sql);
            //setString
            pre.setInt(1, id);
            pre.setString(2, username);
            pre.setString(3, password);
            //execute
            int rows = pre.executeUpdate();
            if(rows>0) {
                System.out.println("sucess");
            } else {
                System.out.println("fali");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //close
            JdbcUtils.closeConnection(conn, pre, null);
        }
    }
     
    //use PreparedStatement
    //delete from user where username="huangzhong"
    public static void dropUser(String username) {
        Connection conn = null;
        PreparedStatement pre = null;
        try {
            //getConnection
            conn = JdbcUtils.getConnection();
            //edit sql
            String sql = "delete from user where username=?";
            //PreparedStatement
            pre = conn.prepareStatement(sql);
            //set value
            pre.setString(1, username);
            //execute sql
            int rows = pre.executeUpdate();
            if(rows>0) {
                System.out.println("success");
            } else {
                System.out.println("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //close Connection
            JdbcUtils.closeConnection(conn, pre, null);
        }
    }
     
    //使用预编译的方式修改用户
    //修改id=9的username=sunquan,password=234
    public static void updateUser(int id,String username,String password) {
        Connection conn = null;
        PreparedStatement pre = null;
        try {
            //getConn
            conn = JdbcUtils.getConnection();
            //sql
            String sql = "update user set username=?,password=? where id=?";
            //preparedStatement
            pre = conn.prepareStatement(sql);
            //setString
            pre.setString(1, username);
            pre.setString(2, password);
            pre.setInt(3, id);
            //execute
            int rows = pre.executeUpdate();
            if(rows>0) {
                System.out.println("success");
            } else {
                System.out.println("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //close
            JdbcUtils.closeConnection(conn, pre, null);
        }
    }
}

jdbc总结

标签:bundle   获取   操作   ase   文件夹   cat   let   creates   dex   

原文地址:http://www.cnblogs.com/liuhuaabcp/p/7955804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!