一、JDBC简介
Java 数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。它JDBC是面向关系型数据库的。
1、JDBC架构:
JDBC API支持两层和三层处理模型进行数据库访问,但在一般的JDBC体系结构由两层组成:
JDBC API: 提供了应用程序对JDBC的管理连接;
JDBC Driver API: 支持JDBC管理到驱动器连接;
JDBC API的使用驱动程序管理器和数据库特定的驱动程序提供透明的连接到异构数据库;
JDBC驱动程序管理器可确保正确的驱动程序来访问每个数据源,该驱动程序管理器能够支持连接到多个异构数据库的多个并发的驱动程序;
以下是结构图,它显示了驱动程序管理器方面的JDBC驱动程序和Java应用程序的位置:
2、常见的JDBC组件:
JDBC API提供了以下接口和类:
DriverManager: 这个类管理数据库驱动程序的列表,内容是否符合从Java应用程序使用的通信子协议正确的数据库驱动程序的连接请求,识别JDBC在一定子协议的第一个驱动器将被用来建立数据库连接;
Driver: 此接口处理与数据库服务器通信,很少直接与驱动程序对象,相反,使用DriverManager中的对象,它管理此类型的对象,它也抽象与驱动程序对象工作相关的详细信息;
Connection : 此接口与接触数据库的所有方法,连接对象表示通信上下文,即,与数据库中的所有的通信是通过唯一的连接对象;
Statement : 可以使用这个接口创建的对象的SQL语句提交到数据库,一些派生的接口接受除执行存储过程的参数;
ResultSet: 这些对象保存从数据库后,执行使用Statement对象的SQL查询中检索数据,它作为一个迭代器,让您可以通过移动它的数据;
SQLException: 这个类处理发生在一个数据库应用程序的任何错误.
二、连接JDBC需要掌握的基本知识
1、数据库的基本操作,
eg:MySQL的安装和基本操作(insert,delete,update,query)
2、java开发工具的使用,
eg:Eclipse/MyEclipse (包括mysql-connector-java-5.0.3-bin.jar的导入)
三、JDBC的连接及代码演示
1、JDBC连接工具类
1)、Configuration.java:可以从.xml文件中连接数据库的配置信息,需要引入dom4j-1.6.1.jar包
1. package cn.java.jdbc;
2.
3. import java.io.InputStream;
4.
5. import org.dom4j.Document;
6. import org.dom4j.DocumentException;
7. import org.dom4j.Element;
8. import org.dom4j.io.SAXReader;
9.
10. public class Configuration {
11.
12. private String url;
13. private String driver;
14. private String username;
15. private String password;
16.
17. public Configuration() {
18. }
19.
20. public Configuration(String url, String driver, String username,
21. String password) {
22. super();
23. this.url = url;
24. this.driver = driver;
25. this.username = username;
26. this.password = password;
27. }
28.
29. public static Configuration getConfigure()
30. {
31.
32. try {
33. class.getResourceAsStream("/db.xml");
34. if (null!=in) {
35. return load(in);
36. }
37. return null;
38. catch (DocumentException e) {
39. e.printStackTrace();
40. return null;
41. }
42.
43. }
44.
45. private static Configuration load(InputStream in) throws DocumentException {
46. new SAXReader();
47. Document doc = reader.read(in);
48. Element jdbc = doc.getRootElement();
49. "url").getText();
50. "driver").getText();
51. "username").getText();
52. "password").getText();
53. new Configuration(url, driver, username, password);
54. return cfg;
55. }
56.
57. public String getUrl() {
58. return url;
59. }
60.
61. public void setUrl(String url) {
62. this.url = url;
63. }
64.
65. public String getDriver() {
66. return driver;
67. }
68.
69. public void setDriver(String driver) {
70. this.driver = driver;
71. }
72.
73. public String getUsername() {
74. return username;
75. }
76.
77. public void setUsername(String username) {
78. this.username = username;
79. }
80.
81. public String getPassword() {
82. return password;
83. }
84.
85. public void setPassword(String password) {
86. this.password = password;
87. }
88.
89.
90. }
2)、db.xml:保存数据库的配置信息
1. <?xml version="1.0" encoding="UTF-8"?>
2. <jdbc>
3. <url>jdbc:mysql://localhost:3306/test</url>
4. <driver>com.mysql.jdbc.Driver</driver>
5. <username>root</username>
6. <password></password>
7. </jdbc>
3)、ConnectionFactory.java:JDBC连接工厂方法之一
1. package cn.java.jdbc;
2.
3. import java.sql.Connection;
4. import java.sql.DriverManager;
5. import java.sql.SQLException;
6.
7. public class ConnectionFactory {
8.
9. private static ConnectionFactory connectionFactory=null;
10. private static Configuration config=Configuration.getConfigure();
11.
12. private ConnectionFactory()
13. {
14. try {
15. Class.forName(config.getDriver());
16. catch (ClassNotFoundException e) {
17. }
18. }
19.
20. public Connection getConnection() throws SQLException
21. {
22.
23. null;
24. try {
25. con=DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
26.
27. return con;
28. finally{
29.
30. // if (null != con) {
31. // con.close();
32. // }
33. }
34.
35. }
36.
37. public static ConnectionFactory getInstance()
38. {
39. if (null==connectionFactory) {
40. new ConnectionFactory();
41. }
42.
43. return connectionFactory;
44.
45. }
46.
47. }
4)、ConnectionFactory2.java:JDBC连接工厂方法之二
1. package cn.java.jdbc;
2.
3. import java.sql.Connection;
4. import java.sql.SQLException;
5.
6. import javax.sql.DataSource;
7.
8. import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
9.
10. public class ConnectionFactory2 {
11.
12.
13. private DataSource ds ;
14.
15. private static ConnectionFactory2 connectionFactory2 = null;
16.
17. private ConnectionFactory2() {
18.
19. new MysqlDataSource() ;
20. "localhost");
21. "test");
22. 3306) ;
23. "root");
24. "utf-8");
25. "");
26. this.ds = myDS ;
27. }
28.
29. public Connection getConnection() throws SQLException {
30.
31. null;
32. try {
33. conn = ds.getConnection() ;
34. false);
35. return conn;
36. catch (SQLException e) {
37. if (null != conn) {
38. conn.close();
39. }
40. throw e;
41. }
42. }
43.
44. public static ConnectionFactory2 getInstance() {
45.
46. if (null == connectionFactory2) {
47. new ConnectionFactory2();
48. }
49. return connectionFactory2;
50.
51. }
52.
53. }
5)、User.java:定义数据库表user中的id和name的bean类,其中id是自动增长的
1. package cn.java.jdbc;
2.
3. public class User {
4. private int id;
5. private String name;
6.
7. public User() {
8. }
9. public User(int id, String name) {
10. this.id = id;
11. this.name = name;
12. }
13.
14. public int getId() {
15. return id;
16. }
17.
18. public void setId(int id) {
19. this.id = id;
20. }
21.
22. public String getName() {
23. return name;
24. }
25.
26. public void setName(String name) {
27. this.name = name;
28. }
29.
30.
31. }
6)、UserDao.java:user表的操作类,实现了insert、delete、update、query等方法
2、JDBC连接的测试类
1. package cn.java.jdbc;
2.
3. import java.io.IOException;
4. import java.sql.Connection;
5. import java.sql.PreparedStatement;
6. import java.sql.ResultSet;
7. import java.sql.SQLException;
8. import java.util.ArrayList;
9. import java.util.List;
10.
11. public class UserDao {
12. private PreparedStatement st = null;
13. private ResultSet rs = null;
14.
15. public UserDao() {
16. }
17.
18. public void insert( Connection con,String name) throws SQLException,IOException {
19. "insert into user(name) values(?) ";
20. try{
21. st=con.prepareStatement(sql);
22. 1, name);
23. st.executeUpdate();
24. finally{
25. if (null!=st) {
26. st.close();
27. }
28.
29. }
30.
31. }
32.
33. public void delete(Connection con,int id) throws SQLException,IOException {
34. "delete from user where id=?";
35. try{
36. st=con.prepareStatement(sql);
37. 1, id);
38. st.executeUpdate();
39. finally{
40. if (null!=st) {
41. st.close();
42. }
43.
44. }
45. }
46.
47. public void update( Connection con,int id,String name) throws SQLException,IOException {
48. "update user set name=? where id=?";
49.
50. try{
51. st=con.prepareStatement(sql);
52. 1, name);
53. 2, id);
54. st.executeUpdate();
55. finally{
56. if (null!=st) {
57. st.close();
58. }
59. }
60.
61. }
62.
63. public User query(Connection con,int index) throws SQLException,IOException{
64. new User();
65. "select * from user where id=?";
66. try{
67. st=con.prepareStatement(sql);
68. 1, index);
69. rs=st.executeQuery();
70. while (rs.next()) {
71. 1));
72. 2));
73. break;
74. }
75.
76. finally{
77. if (null!=rs) {
78. rs.close();
79. }
80.
81. if (null!=st) {
82. st.close();
83. }
84. }
85.
86. return user;
87.
88.
89. }
90.
91. public List<User> queryAll(Connection con) throws SQLException,IOException {
92. new ArrayList<>();
93. "select * from user";
94. try {
95. st=con.prepareStatement(sql);
96. rs=st.executeQuery();
97. while (rs.next()) {
98. new User();
99. 1));
100. 2));
101. list.add(user);
102. }
103.
104. finally{
105. if (null!=rs) {
106. rs.close();
107. }
108.
109. if (null!=st) {
110. st.close();
111. }
112. }
113.
114. return list;
115.
116.
117. }
118.
119. }
1)、TestJdbc.java:数据库测试类
1. package cn.java.jdbc;
2.
3. import java.io.IOException;
4. import java.sql.Connection;
5. import java.sql.SQLException;
6. import java.util.List;
7.
8.
9. public class TestJdbc {
10.
11. public static void main(String[] args) {
12. null;
13. try {
14. con=(Connection) ConnectionFactory.getInstance().getConnection();
15. new UserDao();
16. //con=(Connection) ConnectionFactory2.getInstance().getConnection();
17. if (null!=con) {
18. "Link JDBC SUCESS");
19. //userDao.insert(con, "zhangsir");
20. //userDao.delete(con, 4);
21. //userDao.update(con, 1, "david");
22. List<User> list=userDao.queryAll(con);
23. for (User user : list) {
24. "id="+user.getId()+" name="+user.getName());
25. }
26. }
27.
28. catch (SQLException e) {
29. e.printStackTrace();
30. catch (IOException e) {
31. e.printStackTrace();
32. finally{
33. if (null!=con) {
34. try {
35. con.close();
36. catch (SQLException e) {
37. }
38. }
39. }
40.
41. }
42.
43. }
三、JDBC连接总结
JDBC操作的基本步骤是:
1、创建Connection对象,传入SQL查询命令字符串;
2、获取PreparedStatement对象:通过Connection对象传入SQL查询命令获取;
3、获取ResultSet:对PreparedStatement执行executeUpdate()或者executeQurey()获取;
4、依次关闭打开的对象:先后关闭ResultSet、PreparedStatement和Connection对象.