一、相关概念
1.什么是JDBC
JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
2.数据库驱动
我们安装好数据库之后,我们的应用程序也是不能直接使用数据库的,必须要通过相应的数据库驱动程序,通过驱动程序去和数据库打交道。其实也就是数据库厂商的JDBC接口实现,即对Connection等接口的实现类的jar文件。
二、常用接口
1.Driver接口
Driver接口由数据库厂家提供,作为java开发人员,只需要使用Driver接口就可以了。在编程中要连接数据库,必须先装载特定厂商的数据库驱动程序,不同的数据库有不同的装载方法。如:
装载MySql驱动:Class.forName("com.mysql.jdbc.Driver");
装载Oracle驱动:Class.forName("oracle.jdbc.driver.OracleDriver");
2.Connection接口
Connection与特定数据库的连接(会话),在连接上下文中执行sql语句并返回结果。DriverManager.getConnection(url, user, password)方法建立在JDBC URL中定义的数据库Connection连接上。
连接MySql数据库:Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/database", "user", "password");
连接Oracle数据库:Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:port:database", "user", "password");
连接SqlServer数据库:Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://host:port; DatabaseName=database", "user", "password");
常用方法:
- createStatement():创建向数据库发送sql的statement对象。
- prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象。
- prepareCall(sql):创建执行存储过程的callableStatement对象。
- setAutoCommit(boolean autoCommit):设置事务是否自动提交。
- commit() :在链接上提交事务。
- rollback() :在此链接上回滚事务。
3.Statement接口
用于执行静态SQL语句并返回它所生成结果的对象。
三种Statement类:
- Statement:由createStatement创建,用于发送简单的SQL语句(不带参数)。
- PreparedStatement :继承自Statement接口,由preparedStatement创建,用于发送含有一个或多个参数的SQL语句。PreparedStatement对象比Statement对象的效率更高,并且可以防止SQL注入,所以我们一般都使用PreparedStatement。
- CallableStatement:继承自PreparedStatement接口,由方法prepareCall创建,用于调用存储过程。
常用Statement方法:
- execute(String sql):运行语句,返回是否有结果集
- executeQuery(String sql):运行select语句,返回ResultSet结果集。
- executeUpdate(String sql):运行insert/update/delete操作,返回更新的行数。
- addBatch(String sql) :把多条sql语句放到一个批处理中。
- executeBatch():向数据库发送一批sql语句执行。
4.ResultSet接口
ResultSet提供检索不同类型字段的方法,常用的有:
- getString(int index)、getString(String columnName):获得在数据库里是varchar、char等类型的数据对象。
- getFloat(int index)、getFloat(String columnName):获得在数据库里是Float类型的数据对象。
- getDate(int index)、getDate(String columnName):获得在数据库里是Date类型的数据。
- getBoolean(int index)、getBoolean(String columnName):获得在数据库里是Boolean类型的数据。
- getObject(int index)、getObject(String columnName):获取在数据库里任意类型的数据。
ResultSet还提供了对结果集进行滚动的方法:
- next():移动到下一行
- Previous():移动到前一行
- absolute(int row):移动到指定行
- beforeFirst():移动resultSet的最前面。
- afterLast() :移动到resultSet的最后面。
使用后依次关闭对象及连接:ResultSet → Statement → Connection
三、使用JDBC的步骤
加载JDBC驱动程序 → 建立数据库连接Connection → 创建执行SQL的语句Statement → 处理执行结果ResultSet → 释放资源
1.注册驱动 (只做一次)
方式一:Class.forName(“com.MySQL.jdbc.Driver”);
推荐这种方式,不会对具体的驱动类产生依赖。
方式二:DriverManager.registerDriver(com.mysql.jdbc.Driver);
会造成DriverManager中产生两个一样的驱动,并会对具体的驱动类产生依赖。
2.建立连接
Connection conn = DriverManager.getConnection(url, user, password);
URL用于标识数据库的位置,通过URL地址告诉JDBC程序连接哪个数据库,URL的写法为:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAAByCAIAAABx1FRsAAASVUlEQVR4nO2dTY7ruBHHdRYfQAcwfAoBfQWtvPMJ+gbu3vR+LtBeBD7FGwQZZBXvM5kBkkUQBJiXGXQW+uJHFVkURYm0/j8Qgzd+lERWFfkni7Jf9QUAAADEUW3dAAAAAMUDLQEAABALtAQAAEAs0BIAAACxQEsAAADEAi0BA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lO1ecFalQPUTW++RqWV1VLdlqykTWK0ZLb5dBZwzq2nS5htGSauaSWIabO0ByXhyy15MOa5adU6mBBfl/SW+bVEkvLs9zP/BC/8Oj7QZpvH9CSMln4neBx2PdfaGKmEu2rttb5wRj9Qe8vZaYlm1kjby2hNmeTllhyO85i+nQWriWO5i2yL5n5AyqR/pJoifL1nX6NMn4blP0G7vTatPLqsENL2IOQmb8WDC0pkaW0RBuBylLIM8aIH4lTP+fWTVRJoiX6j6QKv3a3rTW20JKQF6l7S1iCQX+RzTjPnz9lc9butGSS/8Coiy8x/hJ9v0SLW/MlXSW0plfYzYBnvoeobRNpUYeW7IhF/v2Shv72rLvM+gFHR0m4L6F+ECJba2yhJXFFmaqW+j1gSelfmTM+t770nrqk0RL7p89GVRbpsWYc6zeArb/l7jnnB78/oCVlgn9X8dlKeVqy75JwX1JsgZaUCLTk2Qq0pKwCLbELtKREoCXPVqAlZRVoiV2gJSUCLXm2Ai0pq0BL7AItKRGRlhREQM+fl4h42K/RNmS2O/73xx9btz0hC8YtWAE4DAAAQCzQEgAAALFASwAAAMQCLQEAABALtAQAAEAs0BIAAACxQEsAAADE8n/0TD/0Jgby6gAAAABJRU5ErkJggg==" alt="" />
其他参数如:useUnicode=true&characterEncoding=utf8
3.创建执行SQL语句的statement
1 //Statement
2 String id = "5";
3 String sql = "delete from table where id=" + id;
4 Statement st = conn.createStatement();
5 st.executeQuery(sql);
6 //存在sql注入的危险
7 //如果用户传入的id为“5 or 1=1”,那么将删除表中的所有记录
1 //PreparedStatement 有效的防止sql注入(SQL语句在程序运行前已经进行了预编译,当运行时动态地把参数传给PreprareStatement时,即使参数里有敏感字符如 or '1=1'也数据库会作为一个参数一个字段的属性值来处理而不会作为一个SQL指令)
2 String sql = “insert into user (name,pwd) values(?,?)”;
3 PreparedStatement ps = conn.preparedStatement(sql);
4 ps.setString(1, “col_value”); //占位符顺序从1开始
5 ps.setString(2, “123456”); //也可以使用setObject
6 ps.executeQuery();
4.处理执行结果(ResultSet)
1 ResultSet rs = ps.executeQuery();
2 While(rs.next()){
3 rs.getString(“col_name”);
4 rs.getInt(1);
5 //…
6 }
5.释放资源
//数据库连接(Connection)非常耗资源,尽量晚创建,尽量早的释放
//都要加try catch 以防前面关闭出错,后面的就不执行了
1 try {
2 if (rs != null) {
3 rs.close();
4 }
5 } catch (SQLException e) {
6 e.printStackTrace();
7 } finally {
8 try {
9 if (st != null) {
10 st.close();
11 }
12 } catch (SQLException e) {
13 e.printStackTrace();
14 } finally {
15 try {
16 if (conn != null) {
17 conn.close();
18 }
19 } catch (SQLException e) {
20 e.printStackTrace();
21 }
22 }
23 }
四、事务(ACID特点、隔离级别、提交commit、回滚rollback)
1.批处理Batch
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.SQLException;
6 import java.sql.Statement;
7
8 /**
9 * 测试ResultSet结果集的基本用法
10 */
11 public class Demo05 {
12 public static void main(String[] args) {
13 Connection conn = null;
14 Statement stmt = null;
15
16 try {
17 Class.forName("com.mysql.jdbc.Driver");
18 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
19
20 conn.setAutoCommit(false); //设为手动提交
21
22 long start = System.currentTimeMillis();
23
24 stmt = conn.createStatement();
25 for (int i = 0; i < 20000; i++) {
26 stmt.addBatch("insert into t_user (userName,pwd,regTime) values ('hao" + i + "',666666,now())");
27 }
28 stmt.executeBatch();
29 conn.commit(); //提交事务
30
31 long end = System.currentTimeMillis();
32 System.out.println("插入200000条数据,耗时(ms):" + (end - start));
33
34 } catch (ClassNotFoundException e) {
35 e.printStackTrace();
36 } catch (SQLException e) {
37 e.printStackTrace();
38 } finally{
39
40 try {
41 if (stmt!=null) {
42 stmt.close();
43 }
44 } catch (SQLException e) {
45 e.printStackTrace();
46 }
47 try {
48 if (conn!=null) {
49 conn.close();
50 }
51 } catch (SQLException e) {
52 e.printStackTrace();
53 }
54 }
55 }
56 }
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.SQLException;
6 import java.sql.Statement;
7
8 /**
9 * 测试ResultSet结果集的基本用法
10 */
11 public class Demo05 {
12 public static void main(String[] args) {
13 Connection conn = null;
14 Statement stmt = null;
15
16 try {
17 Class.forName("com.mysql.jdbc.Driver");
18 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
19
20 conn.setAutoCommit(false); //设为手动提交
21
22 long start = System.currentTimeMillis();
23
24 stmt = conn.createStatement();
25 for (int i = 0; i < 20000; i++) {
26 stmt.addBatch("insert into t_user (userName,pwd,regTime) values ('hao" + i + "',666666,now())");
27 }
28 stmt.executeBatch();
29 conn.commit(); //提交事务
30
31 long end = System.currentTimeMillis();
32 System.out.println("插入200000条数据,耗时(ms):" + (end - start));
33
34 } catch (ClassNotFoundException e) {
35 e.printStackTrace();
36 } catch (SQLException e) {
37 e.printStackTrace();
38 } finally{
39
40 try {
41 if (stmt!=null) {
42 stmt.close();
43 }
44 } catch (SQLException e) {
45 e.printStackTrace();
46 }
47 try {
48 if (conn!=null) {
49 conn.close();
50 }
51 } catch (SQLException e) {
52 e.printStackTrace();
53 }
54 }
55 }
56 }
2.测试事务的基本概念和用法
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.SQLException;
7
8 /**
9 * 测试事务的基本概念和用法
10 */
11 public class Demo06 {
12 public static void main(String[] args) {
13 Connection conn = null;
14 PreparedStatement ps1 = null;
15 PreparedStatement ps2 = null;
16
17 try {
18 Class.forName("com.mysql.jdbc.Driver");
19 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
20
21 conn.setAutoCommit(false); //JDBC中默认是true,自动提交事务
22
23 ps1 = conn.prepareStatement("insert into t_user(userName,pwd)values(?,?)"); //事务开始
24 ps1.setObject(1, "小高");
25 ps1.setObject(2, "123");
26 ps1.execute();
27 System.out.println("第一次插入");
28
29 try {
30 Thread.sleep(5000);
31 } catch (InterruptedException e) {
32 e.printStackTrace();
33 }
34
35 ps2 = conn.prepareStatement("insert into t_user(userName,pwd)values(?,?,?)"); //模拟执行失败(values的参数写成三个了)
36 //insert时出现异常,执行conn.rollback
37 ps2.setObject(1, "小张");
38 ps2.setObject(2, "678");
39 ps2.execute();
40 System.out.println("第二次插入");
41
42 conn.commit();
43
44 } catch (ClassNotFoundException e) {
45 e.printStackTrace();
46 try {
47 conn.rollback();
48 } catch (SQLException e1) {
49 e1.printStackTrace();
50 }
51 } catch (SQLException e) {
52 e.printStackTrace();
53 } finally{
54
55 try {
56 if (ps1!=null) {
57 ps1.close();
58 }
59 } catch (SQLException e) {
60 e.printStackTrace();
61 }
62 try {
63 if (ps2!=null) {
64 ps2.close();
65 }
66 } catch (SQLException e) {
67 e.printStackTrace();
68 }
69 try {
70 if (conn!=null) {
71 conn.close();
72 }
73 } catch (SQLException e) {
74 e.printStackTrace();
75 }
76 }
77 }
78 }
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.SQLException;
7
8 /**
9 * 测试事务的基本概念和用法
10 */
11 public class Demo06 {
12 public static void main(String[] args) {
13 Connection conn = null;
14 PreparedStatement ps1 = null;
15 PreparedStatement ps2 = null;
16
17 try {
18 Class.forName("com.mysql.jdbc.Driver");
19 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
20
21 conn.setAutoCommit(false); //JDBC中默认是true,自动提交事务
22
23 ps1 = conn.prepareStatement("insert into t_user(userName,pwd)values(?,?)"); //事务开始
24 ps1.setObject(1, "小高");
25 ps1.setObject(2, "123");
26 ps1.execute();
27 System.out.println("第一次插入");
28
29 try {
30 Thread.sleep(5000);
31 } catch (InterruptedException e) {
32 e.printStackTrace();
33 }
34
35 ps2 = conn.prepareStatement("insert into t_user(userName,pwd)values(?,?,?)"); //模拟执行失败(values的参数写成三个了)
36 //insert时出现异常,执行conn.rollback
37 ps2.setObject(1, "小张");
38 ps2.setObject(2, "678");
39 ps2.execute();
40 System.out.println("第二次插入");
41
42 conn.commit();
43
44 } catch (ClassNotFoundException e) {
45 e.printStackTrace();
46 try {
47 conn.rollback();
48 } catch (SQLException e1) {
49 e1.printStackTrace();
50 }
51 } catch (SQLException e) {
52 e.printStackTrace();
53 } finally{
54
55 try {
56 if (ps1!=null) {
57 ps1.close();
58 }
59 } catch (SQLException e) {
60 e.printStackTrace();
61 }
62 try {
63 if (ps2!=null) {
64 ps2.close();
65 }
66 } catch (SQLException e) {
67 e.printStackTrace();
68 }
69 try {
70 if (conn!=null) {
71 conn.close();
72 }
73 } catch (SQLException e) {
74 e.printStackTrace();
75 }
76 }
77 }
78 }
1 第一次插入
2 java.sql.SQLException: No value specified for parameter 3
3 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
4 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
5 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
6 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
7 at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2611)
8 at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2586)
9 at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2510)
10 at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1316)
11 at com.test.jdbc.Demo06.main(Demo06.java:39)
1 第一次插入
2 java.sql.SQLException: No value specified for parameter 3
3 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
4 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
5 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
6 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
7 at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2611)
8 at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2586)
9 at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2510)
10 at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1316)
11 at com.test.jdbc.Demo06.main(Demo06.java:39)
五、时间处理(Date和Time以及Timestamp区别、随机日期生成)
java.util.Date
- 子类:java.sql.Date
- 子类:java.sql.Time
- 子类:java.sql.Timestamp
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.SQLException;
7 import java.sql.Timestamp;
8 import java.util.Random;
9
10 /**
11 * 测试时间处理(java.sql.Date,Time,Timestamp)
12 */
13 public class Demo07 {
14 public static void main(String[] args) {
15 Connection conn = null;
16 PreparedStatement ps = null;
17
18 try {
19 Class.forName("com.mysql.jdbc.Driver");
20 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
21
22 for (int i = 0; i < 1000; i++) {
23
24 ps = conn.prepareStatement("insert into t_user(userName,pwd,regTime,lastLoginTime)values(?,?,?,?)");
25 ps.setObject(1, "小高" + i);
26 ps.setObject(2, "123");
27
28 //
29 int random = 1000000000 + new Random().nextInt(1000000000); //随机时间
30
31 java.sql.Date date = new java.sql.Date(System.currentTimeMillis() - random); //插入随机时间
32 java.sql.Timestamp stamp = new Timestamp(System.currentTimeMillis()); //如果需要插入指定时间,可以使用Calendar、DateFormat
33 ps.setDate(3, date);
34 ps.setTimestamp(4, stamp);
35 //
36 ps.execute();
37 }
38
39 System.out.println("插入");
40
41 } catch (ClassNotFoundException e) {
42 e.printStackTrace();
43 } catch (SQLException e) {
44 e.printStackTrace();
45 } finally{
46
47 try {
48 if (ps!=null) {
49 ps.close();
50 }
51 } catch (SQLException e) {
52 e.printStackTrace();
53 }
54 try {
55 if (conn!=null) {
56 conn.close();
57 }
58 } catch (SQLException e) {
59 e.printStackTrace();
60 }
61 }
62 }
63 }
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.PreparedStatement;
6 import java.sql.SQLException;
7 import java.sql.Timestamp;
8 import java.util.Random;
9
10 /**
11 * 测试时间处理(java.sql.Date,Time,Timestamp)
12 */
13 public class Demo07 {
14 public static void main(String[] args) {
15 Connection conn = null;
16 PreparedStatement ps = null;
17
18 try {
19 Class.forName("com.mysql.jdbc.Driver");
20 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
21
22 for (int i = 0; i < 1000; i++) {
23
24 ps = conn.prepareStatement("insert into t_user(userName,pwd,regTime,lastLoginTime)values(?,?,?,?)");
25 ps.setObject(1, "小高" + i);
26 ps.setObject(2, "123");
27
28 //
29 int random = 1000000000 + new Random().nextInt(1000000000); //随机时间
30
31 java.sql.Date date = new java.sql.Date(System.currentTimeMillis() - random); //插入随机时间
32 java.sql.Timestamp stamp = new Timestamp(System.currentTimeMillis()); //如果需要插入指定时间,可以使用Calendar、DateFormat
33 ps.setDate(3, date);
34 ps.setTimestamp(4, stamp);
35 //
36 ps.execute();
37 }
38
39 System.out.println("插入");
40
41 } catch (ClassNotFoundException e) {
42 e.printStackTrace();
43 } catch (SQLException e) {
44 e.printStackTrace();
45 } finally{
46
47 try {
48 if (ps!=null) {
49 ps.close();
50 }
51 } catch (SQLException e) {
52 e.printStackTrace();
53 }
54 try {
55 if (conn!=null) {
56 conn.close();
57 }
58 } catch (SQLException e) {
59 e.printStackTrace();
60 }
61 }
62 }
63 }
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.Date;
5 import java.sql.DriverManager;
6 import java.sql.PreparedStatement;
7 import java.sql.ResultSet;
8 import java.sql.SQLException;
9 import java.text.DateFormat;
10 import java.text.ParseException;
11 import java.text.SimpleDateFormat;
12
13 /**
14 * 测试时间处理(java.sql.Date,Time,Timestamp),取出指定时间段的数据
15 */
16 public class Demo08 {
17
18 /**
19 * 将字符串代表的时间转为long数字(格式:yyyy-MM-dd hh:mm:ss)
20 * @param dateStr
21 * @return
22 */
23 public static long str2DateTime(String dateStr){
24 DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
25
26 try {
27 return format.parse(dateStr).getTime();
28 } catch (ParseException e) {
29 e.printStackTrace();
30 return 0;
31 }
32 }
33
34 public static void main(String[] args) {
35 Connection conn = null;
36 PreparedStatement ps = null;
37 ResultSet rs = null;
38
39 try {
40 Class.forName("com.mysql.jdbc.Driver");
41 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
42
43 //
44 ps = conn.prepareStatement("select * from t_user where regTime > ? and regTime < ?");
45 java.sql.Date start = new java.sql.Date(str2DateTime("2016-06-20 00:00:00"));
46 java.sql.Date end = new java.sql.Date(str2DateTime("2016-06-24 00:00:00"));
47
48 ps.setObject(1, start);
49 ps.setObject(2, end);
50
51 rs = ps.executeQuery();
52 while(rs.next()){
53 System.out.println(rs.getInt("id") + "--" + rs.getString("userName")+"--"+rs.getDate("regTime"));
54 }
55 //
56
57 } catch (ClassNotFoundException e) {
58 e.printStackTrace();
59 } catch (SQLException e) {
60 e.printStackTrace();
61 } finally{
62
63 try {
64 if (ps!=null) {
65 ps.close();
66 }
67 } catch (SQLException e) {
68 e.printStackTrace();
69 }
70 try {
71 if (conn!=null) {
72 conn.close();
73 }
74 } catch (SQLException e) {
75 e.printStackTrace();
76 }
77 }
78 }
79 }
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.Date;
5 import java.sql.DriverManager;
6 import java.sql.PreparedStatement;
7 import java.sql.ResultSet;
8 import java.sql.SQLException;
9 import java.text.DateFormat;
10 import java.text.ParseException;
11 import java.text.SimpleDateFormat;
12
13 /**
14 * 测试时间处理(java.sql.Date,Time,Timestamp),取出指定时间段的数据
15 */
16 public class Demo08 {
17
18 /**
19 * 将字符串代表的时间转为long数字(格式:yyyy-MM-dd hh:mm:ss)
20 * @param dateStr
21 * @return
22 */
23 public static long str2DateTime(String dateStr){
24 DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
25
26 try {
27 return format.parse(dateStr).getTime();
28 } catch (ParseException e) {
29 e.printStackTrace();
30 return 0;
31 }
32 }
33
34 public static void main(String[] args) {
35 Connection conn = null;
36 PreparedStatement ps = null;
37 ResultSet rs = null;
38
39 try {
40 Class.forName("com.mysql.jdbc.Driver");
41 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
42
43 //
44 ps = conn.prepareStatement("select * from t_user where regTime > ? and regTime < ?");
45 java.sql.Date start = new java.sql.Date(str2DateTime("2016-06-20 00:00:00"));
46 java.sql.Date end = new java.sql.Date(str2DateTime("2016-06-24 00:00:00"));
47
48 ps.setObject(1, start);
49 ps.setObject(2, end);
50
51 rs = ps.executeQuery();
52 while(rs.next()){
53 System.out.println(rs.getInt("id") + "--" + rs.getString("userName")+"--"+rs.getDate("regTime"));
54 }
55 //
56
57 } catch (ClassNotFoundException e) {
58 e.printStackTrace();
59 } catch (SQLException e) {
60 e.printStackTrace();
61 } finally{
62
63 try {
64 if (ps!=null) {
65 ps.close();
66 }
67 } catch (SQLException e) {
68 e.printStackTrace();
69 }
70 try {
71 if (conn!=null) {
72 conn.close();
73 }
74 } catch (SQLException e) {
75 e.printStackTrace();
76 }
77 }
78 }
79 }
六、CLOB文本大对象操作
1 package com.test.jdbc;
2
3 import java.io.BufferedReader;
4 import java.io.ByteArrayInputStream;
5 import java.io.File;
6 import java.io.FileReader;
7 import java.io.InputStreamReader;
8 import java.io.Reader;
9 import java.sql.Clob;
10 import java.sql.Connection;
11 import java.sql.DriverManager;
12 import java.sql.PreparedStatement;
13 import java.sql.ResultSet;
14 import java.sql.SQLException;
15
16 /**
17 * 测试CLOB 文本大对象的使用
18 * 包含:将字符串、文件内容插入数据库中的CLOB字段和将CLOB字段值取出来的操作。
19 */
20 public class Demo09 {
21 public static void main(String[] args) {
22 Connection conn = null;
23 PreparedStatement ps = null;
24 PreparedStatement ps2 = null;
25 ResultSet rs = null;
26 Reader r = null;
27
28 try {
29 Class.forName("com.mysql.jdbc.Driver");
30 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
31
32 //插入//
33 ps = conn.prepareStatement("insert into t_user(userName,myInfo)values(?,?)");
34 ps.setString(1, "小高");
35
36 //将文本文件内容直接输入到数据库中
37 // ps.setClob(2, new FileReader(new File("G:/JAVA/test/a.txt")));
38
39 //将程序中的字符串输入到数据库中的CLOB字段中
40 ps.setClob(2, new BufferedReader(new InputStreamReader(new ByteArrayInputStream("aaaa".getBytes()))));
41
42 ps.executeUpdate();
43 System.out.println("插入");
44 //
45
46 //查询//
47 ps2 = conn.prepareStatement("select * from t_user where id=?");
48 ps2.setObject(1, 223021);
49
50 rs = ps2.executeQuery();
51 System.out.println("查询");
52 while (rs.next()) {
53 Clob c = rs.getClob("myInfo");
54 r = c.getCharacterStream();
55 int temp = 0;
56 while ((temp=r.read())!=-1) {
57 System.out.print((char)temp);
58 }
59 }
60
61 } catch (ClassNotFoundException e) {
62 e.printStackTrace();
63 } catch (Exception e) {
64 e.printStackTrace();
65 } finally{
66
67 try {
68 if (r!=null) {
69 r.close();
70 }
71 } catch (Exception e) {
72 e.printStackTrace();
73 }
74 try {
75 if (rs!=null) {
76 rs.close();
77 }
78 } catch (SQLException e) {
79 e.printStackTrace();
80 }
81 try {
82 if (ps2!=null) {
83 ps2.close();
84 }
85 } catch (SQLException e) {
86 e.printStackTrace();
87 }
88 try {
89 if (ps!=null) {
90 ps.close();
91 }
92 } catch (SQLException e) {
93 e.printStackTrace();
94 }
95 try {
96 if (conn!=null) {
97 conn.close();
98 }
99 } catch (SQLException e) {
100 e.printStackTrace();
101 }
102 }
103 }
104 }
1 package com.test.jdbc;
2
3 import java.io.BufferedReader;
4 import java.io.ByteArrayInputStream;
5 import java.io.File;
6 import java.io.FileReader;
7 import java.io.InputStreamReader;
8 import java.io.Reader;
9 import java.sql.Clob;
10 import java.sql.Connection;
11 import java.sql.DriverManager;
12 import java.sql.PreparedStatement;
13 import java.sql.ResultSet;
14 import java.sql.SQLException;
15
16 /**
17 * 测试CLOB 文本大对象的使用
18 * 包含:将字符串、文件内容插入数据库中的CLOB字段和将CLOB字段值取出来的操作。
19 */
20 public class Demo09 {
21 public static void main(String[] args) {
22 Connection conn = null;
23 PreparedStatement ps = null;
24 PreparedStatement ps2 = null;
25 ResultSet rs = null;
26 Reader r = null;
27
28 try {
29 Class.forName("com.mysql.jdbc.Driver");
30 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
31
32 //插入//
33 ps = conn.prepareStatement("insert into t_user(userName,myInfo)values(?,?)");
34 ps.setString(1, "小高");
35
36 //将文本文件内容直接输入到数据库中
37 // ps.setClob(2, new FileReader(new File("G:/JAVA/test/a.txt")));
38
39 //将程序中的字符串输入到数据库中的CLOB字段中
40 ps.setClob(2, new BufferedReader(new InputStreamReader(new ByteArrayInputStream("aaaa".getBytes()))));
41
42 ps.executeUpdate();
43 System.out.println("插入");
44 //
45
46 //查询//
47 ps2 = conn.prepareStatement("select * from t_user where id=?");
48 ps2.setObject(1, 223021);
49
50 rs = ps2.executeQuery();
51 System.out.println("查询");
52 while (rs.next()) {
53 Clob c = rs.getClob("myInfo");
54 r = c.getCharacterStream();
55 int temp = 0;
56 while ((temp=r.read())!=-1) {
57 System.out.print((char)temp);
58 }
59 }
60
61 } catch (ClassNotFoundException e) {
62 e.printStackTrace();
63 } catch (Exception e) {
64 e.printStackTrace();
65 } finally{
66
67 try {
68 if (r!=null) {
69 r.close();
70 }
71 } catch (Exception e) {
72 e.printStackTrace();
73 }
74 try {
75 if (rs!=null) {
76 rs.close();
77 }
78 } catch (SQLException e) {
79 e.printStackTrace();
80 }
81 try {
82 if (ps2!=null) {
83 ps2.close();
84 }
85 } catch (SQLException e) {
86 e.printStackTrace();
87 }
88 try {
89 if (ps!=null) {
90 ps.close();
91 }
92 } catch (SQLException e) {
93 e.printStackTrace();
94 }
95 try {
96 if (conn!=null) {
97 conn.close();
98 }
99 } catch (SQLException e) {
100 e.printStackTrace();
101 }
102 }
103 }
104 }
七、BLOB二进制大对象的使用
1 package com.test.jdbc;
2
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7 import java.sql.Blob;
8 import java.sql.Connection;
9 import java.sql.DriverManager;
10 import java.sql.PreparedStatement;
11 import java.sql.ResultSet;
12 import java.sql.SQLException;
13
14 /**
15 * 测试BLOB 二进制大对象的使用
16 */
17 public class Demo10 {
18 public static void main(String[] args) {
19 Connection conn = null;
20 PreparedStatement ps = null;
21 PreparedStatement ps2 = null;
22 ResultSet rs = null;
23 InputStream is = null;
24 OutputStream os = null;
25
26 try {
27 Class.forName("com.mysql.jdbc.Driver");
28 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
29
30 //插入//
31 ps = conn.prepareStatement("insert into t_user(userName,headImg)values(?,?)");
32 ps.setString(1, "小高");
33 ps.setBlob(2, new FileInputStream("G:/JAVA/test/d.jpg"));
34 ps.execute();
35 //
36
37 //查询//
38 ps2 = conn.prepareStatement("select * from t_user where id=?");
39 ps2.setObject(1, 223024);
40
41 rs = ps2.executeQuery();
42 System.out.println("查询");
43 while (rs.next()) {
44 Blob b = rs.getBlob("headImg");
45 is = b.getBinaryStream();
46 os = new FileOutputStream("G:/JAVA/test/h.jpg");
47
48 int temp = 0;
49 while ((temp=is.read())!=-1) {
50 os.write(temp);
51 }
52 }
53
54 } catch (ClassNotFoundException e) {
55 e.printStackTrace();
56 } catch (Exception e) {
57 e.printStackTrace();
58 } finally{
59
60 try {
61 if (os!=null) {
62 os.close();
63 }
64 } catch (Exception e) {
65 e.printStackTrace();
66 }
67 try {
68 if (is!=null) {
69 is.close();
70 }
71 } catch (Exception e) {
72 e.printStackTrace();
73 }
74 try {
75 if (rs!=null) {
76 rs.close();
77 }
78 } catch (SQLException e) {
79 e.printStackTrace();
80 }
81 try {
82 if (ps2!=null) {
83 ps2.close();
84 }
85 } catch (SQLException e) {
86 e.printStackTrace();
87 }
88 try {
89 if (ps!=null) {
90 ps.close();
91 }
92 } catch (SQLException e) {
93 e.printStackTrace();
94 }
95 try {
96 if (conn!=null) {
97 conn.close();
98 }
99 } catch (SQLException e) {
100 e.printStackTrace();
101 }
102 }
103 }
104 }
1 package com.test.jdbc;
2
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7 import java.sql.Blob;
8 import java.sql.Connection;
9 import java.sql.DriverManager;
10 import java.sql.PreparedStatement;
11 import java.sql.ResultSet;
12 import java.sql.SQLException;
13
14 /**
15 * 测试BLOB 二进制大对象的使用
16 */
17 public class Demo10 {
18 public static void main(String[] args) {
19 Connection conn = null;
20 PreparedStatement ps = null;
21 PreparedStatement ps2 = null;
22 ResultSet rs = null;
23 InputStream is = null;
24 OutputStream os = null;
25
26 try {
27 Class.forName("com.mysql.jdbc.Driver");
28 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","mysql");
29
30 //插入//
31 ps = conn.prepareStatement("insert into t_user(userName,headImg)values(?,?)");
32 ps.setString(1, "小高");
33 ps.setBlob(2, new FileInputStream("G:/JAVA/test/d.jpg"));
34 ps.execute();
35 //
36
37 //查询//
38 ps2 = conn.prepareStatement("select * from t_user where id=?");
39 ps2.setObject(1, 223024);
40
41 rs = ps2.executeQuery();
42 System.out.println("查询");
43 while (rs.next()) {
44 Blob b = rs.getBlob("headImg");
45 is = b.getBinaryStream();
46 os = new FileOutputStream("G:/JAVA/test/h.jpg");
47
48 int temp = 0;
49 while ((temp=is.read())!=-1) {
50 os.write(temp);
51 }
52 }
53
54 } catch (ClassNotFoundException e) {
55 e.printStackTrace();
56 } catch (Exception e) {
57 e.printStackTrace();
58 } finally{
59
60 try {
61 if (os!=null) {
62 os.close();
63 }
64 } catch (Exception e) {
65 e.printStackTrace();
66 }
67 try {
68 if (is!=null) {
69 is.close();
70 }
71 } catch (Exception e) {
72 e.printStackTrace();
73 }
74 try {
75 if (rs!=null) {
76 rs.close();
77 }
78 } catch (SQLException e) {
79 e.printStackTrace();
80 }
81 try {
82 if (ps2!=null) {
83 ps2.close();
84 }
85 } catch (SQLException e) {
86 e.printStackTrace();
87 }
88 try {
89 if (ps!=null) {
90 ps.close();
91 }
92 } catch (SQLException e) {
93 e.printStackTrace();
94 }
95 try {
96 if (conn!=null) {
97 conn.close();
98 }
99 } catch (SQLException e) {
100 e.printStackTrace();
101 }
102 }
103 }
104 }
八、总结(简单封装、资源文件properties处理连接信息)
1 #右击该properties文件--properties--Resource--Text file encoding,选中other,选择其它编码方式。
2 #如UTF-8或GBK,这样就能在properties里面输入中文,而不会自动转成Unicode了。
3
4 #java中的properties文件是一种配置文件,主要用于表达配置信息。
5 #文件类型为*.properties,格式为文本文件,文件内容是"键=值"的格式。
6 #在properties文件中,可以用"#"来作注释
7
8 #MySQL连接配置
9 mysqlDriver=com.mysql.jdbc.Driver
10 mysqlURL=jdbc:mysql://localhost:3306/testjdbc
11 mysqlUser=root
12 mysqlPwd=mysql
13
14 #Oracle连接配置
15 #...
1 #右击该properties文件--properties--Resource--Text file encoding,选中other,选择其它编码方式。
2 #如UTF-8或GBK,这样就能在properties里面输入中文,而不会自动转成Unicode了。
3
4 #java中的properties文件是一种配置文件,主要用于表达配置信息。
5 #文件类型为*.properties,格式为文本文件,文件内容是"键=值"的格式。
6 #在properties文件中,可以用"#"来作注释
7
8 #MySQL连接配置
9 mysqlDriver=com.mysql.jdbc.Driver
10 mysqlURL=jdbc:mysql://localhost:3306/testjdbc
11 mysqlUser=root
12 mysqlPwd=mysql
13
14 #Oracle连接配置
15 #...
package com.test.jdbc;
2
3 import java.io.IOException;
4 import java.sql.Connection;
5 import java.sql.DriverManager;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.sql.Statement;
9 import java.util.Properties;
10
11 public class JDBCUtil {
12
13 static Properties pros = null; //可以帮助读取和处理资源文件中的信息
14
15 static { //加载JDBCUtil类的时候调用
16 pros = new Properties();
17 try {
18 pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
19 } catch (IOException e) {
20 e.printStackTrace();
21 }
22 }
23
24 public static Connection getMysqlConn(){
25 try {
26 Class.forName(pros.getProperty("mysqlDriver"));
27 return DriverManager.getConnection(pros.getProperty("mysqlURL"),
28 pros.getProperty("mysqlUser"),pros.getProperty("mysqlPwd"));
29 } catch (Exception e) {
30 e.printStackTrace();
31 return null;
32 }
33 }
34 //可以重载多个,这里就懒得写了
35 public static void close(ResultSet rs,Statement st,Connection conn){
36
37 try {
38 if (rs!=null) {
39 rs.close();
40 }
41 } catch (SQLException e) {
42 e.printStackTrace();
43 }
44 try {
45 if (st!=null) {
46 st.close();
47 }
48 } catch (SQLException e) {
49 e.printStackTrace();
50 }
51 try {
52 if (conn!=null) {
53 conn.close();
54 }
55 } catch (SQLException e) {
56 e.printStackTrace();
57 }
58 }
59 }
1 package com.test.jdbc;
2
3 import java.io.IOException;
4 import java.sql.Connection;
5 import java.sql.DriverManager;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.sql.Statement;
9 import java.util.Properties;
10
11 public class JDBCUtil {
12
13 static Properties pros = null; //可以帮助读取和处理资源文件中的信息
14
15 static { //加载JDBCUtil类的时候调用
16 pros = new Properties();
17 try {
18 pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
19 } catch (IOException e) {
20 e.printStackTrace();
21 }
22 }
23
24 public static Connection getMysqlConn(){
25 try {
26 Class.forName(pros.getProperty("mysqlDriver"));
27 return DriverManager.getConnection(pros.getProperty("mysqlURL"),
28 pros.getProperty("mysqlUser"),pros.getProperty("mysqlPwd"));
29 } catch (Exception e) {
30 e.printStackTrace();
31 return null;
32 }
33 }
34 //可以重载多个,这里就懒得写了
35 public static void close(ResultSet rs,Statement st,Connection conn){
36
37 try {
38 if (rs!=null) {
39 rs.close();
40 }
41 } catch (SQLException e) {
42 e.printStackTrace();
43 }
44 try {
45 if (st!=null) {
46 st.close();
47 }
48 } catch (SQLException e) {
49 e.printStackTrace();
50 }
51 try {
52 if (conn!=null) {
53 conn.close();
54 }
55 } catch (SQLException e) {
56 e.printStackTrace();
57 }
58 }
59 }
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.PreparedStatement;
5 import java.sql.ResultSet;
6
7 /**
8 * 测试使用JDBCUtil工具类来简化JDBC开发
9 */
10 public class Demo11 {
11 public static void main(String[] args) {
12 Connection conn = null;
13 PreparedStatement ps = null;
14 ResultSet rs = null;
15
16 try {
17 conn = JDBCUtil.getMysqlConn();
18
19 ps = conn.prepareStatement("insert into t_user (userName) values (?)");
20 ps.setString(1, "小高高");
21 ps.execute();
22
23 } catch (Exception e) {
24 e.printStackTrace();
25 } finally{
26 JDBCUtil.close(rs, ps, conn);
27 }
28 }
29 }
1 package com.test.jdbc;
2
3 import java.sql.Connection;
4 import java.sql.PreparedStatement;
5 import java.sql.ResultSet;
6
7 /**
8 * 测试使用JDBCUtil工具类来简化JDBC开发
9 */
10 public class Demo11 {
11 public static void main(String[] args) {
12 Connection conn = null;
13 PreparedStatement ps = null;
14 ResultSet rs = null;
15
16 try {
17 conn = JDBCUtil.getMysqlConn();
18
19 ps = conn.prepareStatement("insert into t_user (userName) values (?)");
20 ps.setString(1, "小高高");
21 ps.execute();
22
23 } catch (Exception e) {
24 e.printStackTrace();
25 } finally{
26 JDBCUtil.close(rs, ps, conn);
27 }
28 }
29 }