jdbc总结

转载于: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的 user name =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 );
         }
     }
}

转载于:https://www.cnblogs.com/liuhuaabcp/p/7955804.html

一、概述: JDBC从物理结构上说就是Java语言访问数据库的一套接口集合。从本质上来说就是调用者(程序员)和实现者(数据库厂商)之间的协议。JDBC的实现由数据库厂商以驱动程序的形式提供。JDBC API 使得开发人员可以使用纯Java的方式来连接数据库,并进行操作。 ODBC:基于C语言的数据库访问接口。 JDBC也就是Java版的ODBC。 JDBC的特性:高度的一致性、简单性(常用的接口只有4、5个)。 1.在JDBC中包括了两个包:java.sql和javax.sql。 ① java.sql 基本功能。这个包中的类和接口主要针对基本的数据库编程服务,如生成连接、执行语句以及准备语句和运行批处理查询等。同时也有一些高级的处理,比如批处理更新、事务隔离和可滚动结果集等。 ② javax.sql 扩展功能。它主要为数据库方面的高级操作提供了接口和类。如为连接管理、分布式事务和旧有的连接提供了更好的抽象,它引入了容器管理的连接池、分布式事务和行集等。 注:除了标出的Class,其它均为接口。 API 说明 java.sql.Connection 与特定数据库的连接(会话)。能够通过getMetaData方法获得数据库提供的信息、所支持的SQL语法、存储过程和此连接的功能等信息。代表了数据库java.sql.Driver 每个驱动程序类必需实现的接口,同时,每个数据库驱动程序都应该提供一个实现Driver接口的类。 java.sql.DriverManager (Class) 管理一组JDBC驱动程序的基本服务。作为初始化的一部分,此接口会尝试加载在”jdbc.drivers”系统属性中引用的驱动程序。只是一个辅助类,是工具。 java.sql.Statement 用于执行静态SQL语句并返回其生成结果的对象。 java.sql.PreparedStatement 继承Statement接口,表示预编译的SQL语句的对象,SQL语句被预编译并且存储在PreparedStatement对象中。然后可以使用此对象高效地多次执行该语句。 java.sql.CallableStatement 用来访问数据库中的存储过程。它提供了一些方法来指定语句所使用的输入/输出参数。 java.sql.ResultSet 指的是查询返回的数据库结果集。 java.sql.ResultSetMetaData 可用于获取关于ResultSet对象中列的类型和属性信息的对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值