当前位置:   article > 正文

java jdbc连接数据库(使用mysql进行连接)_import com.mysql.jdbc.jdbc2.optional.mysqldatasour

import com.mysql.jdbc.jdbc2.optional.mysqldatasource

一、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. import java.io.InputStream;
  3. import org.dom4j.Document;
  4. import org.dom4j.DocumentException;
  5. import org.dom4j.Element;
  6. import org.dom4j.io.SAXReader;
  7. public class Configuration {
  8. private String url;
  9. private String driver;
  10. private String username;
  11. private String password;
  12. public Configuration() {
  13. }
  14. public Configuration(String url, String driver, String username,
  15. String password) {
  16. super();
  17. this.url = url;
  18. this.driver = driver;
  19. this.username = username;
  20. this.password = password;
  21. }
  22. public static Configuration getConfigure()
  23. {
  24. try {
  25. InputStream in = Configuration.class.getResourceAsStream("/db.xml");
  26. if (null!=in) {
  27. return load(in);
  28. }
  29. return null;
  30. } catch (DocumentException e) {
  31. e.printStackTrace();
  32. return null;
  33. }
  34. }
  35. private static Configuration load(InputStream in) throws DocumentException {
  36. SAXReader reader = new SAXReader();
  37. Document doc = reader.read(in);
  38. Element jdbc = doc.getRootElement();
  39. String url = jdbc.element("url").getText();
  40. String driver = jdbc.element("driver").getText();
  41. String username = jdbc.element("username").getText();
  42. String password = jdbc.element("password").getText();
  43. Configuration cfg = new Configuration(url, driver, username, password);
  44. return cfg;
  45. }
  46. public String getUrl() {
  47. return url;
  48. }
  49. public void setUrl(String url) {
  50. this.url = url;
  51. }
  52. public String getDriver() {
  53. return driver;
  54. }
  55. public void setDriver(String driver) {
  56. this.driver = driver;
  57. }
  58. public String getUsername() {
  59. return username;
  60. }
  61. public void setUsername(String username) {
  62. this.username = username;
  63. }
  64. public String getPassword() {
  65. return password;
  66. }
  67. public void setPassword(String password) {
  68. this.password = password;
  69. }
  70. }


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. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. public class ConnectionFactory {
  6. private static ConnectionFactory connectionFactory=null;
  7. private static Configuration config=Configuration.getConfigure();
  8. private ConnectionFactory()
  9. {
  10. try {
  11. Class.forName(config.getDriver());
  12. } catch (ClassNotFoundException e) {
  13. }
  14. }
  15. public Connection getConnection() throws SQLException
  16. {
  17. Connection con=null;
  18. try {
  19. con=DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
  20. return con;
  21. }finally{
  22. // if (null != con) {
  23. // con.close();
  24. // }
  25. }
  26. }
  27. public static ConnectionFactory getInstance()
  28. {
  29. if (null==connectionFactory) {
  30. connectionFactory=new ConnectionFactory();
  31. }
  32. return connectionFactory;
  33. }
  34. }

4)、ConnectionFactory2.java:JDBC连接工厂方法之二

  1. package cn.java.jdbc;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import javax.sql.DataSource;
  5. import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
  6. public class ConnectionFactory2 {
  7. private DataSource ds ;
  8. private static ConnectionFactory2 connectionFactory2 = null;
  9. private ConnectionFactory2() {
  10. MysqlDataSource myDS = new MysqlDataSource() ;
  11. myDS.setServerName("localhost");
  12. myDS.setDatabaseName("test");
  13. myDS.setPort(3306) ;
  14. myDS.setUser("root");
  15. myDS.setCharacterEncoding("utf-8");
  16. myDS.setPassword("");
  17. this.ds = myDS ;
  18. }
  19. public Connection getConnection() throws SQLException {
  20. Connection conn = null;
  21. try {
  22. conn = ds.getConnection() ;
  23. conn.setAutoCommit(false);
  24. return conn;
  25. } catch (SQLException e) {
  26. if (null != conn) {
  27. conn.close();
  28. }
  29. throw e;
  30. }
  31. }
  32. public static ConnectionFactory2 getInstance() {
  33. if (null == connectionFactory2) {
  34. connectionFactory2 = new ConnectionFactory2();
  35. }
  36. return connectionFactory2;
  37. }
  38. }

5)、User.java:定义数据库表user中的id和name的bean类,其中id是自动增长的

  1. package cn.java.jdbc;
  2. public class User {
  3. private int id;
  4. private String name;
  5. public User() {
  6. }
  7. public User(int id, String name) {
  8. this.id = id;
  9. this.name = name;
  10. }
  11. public int getId() {
  12. return id;
  13. }
  14. public void setId(int id) {
  15. this.id = id;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. }

6)、UserDao.java:user表的操作类,实现了insert、delete、update、query等方法

  1. package cn.java.jdbc;
  2. import java.io.IOException;
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. public class UserDao {
  10. private PreparedStatement st = null;
  11. private ResultSet rs = null;
  12. public UserDao() {
  13. }
  14. public void insert( Connection con,String name) throws SQLException,IOException {
  15. String sql="insert into user(name) values(?) ";
  16. try{
  17. st=con.prepareStatement(sql);
  18. st.setString(1, name);
  19. st.executeUpdate();
  20. }finally{
  21. if (null!=st) {
  22. st.close();
  23. }
  24. }
  25. }
  26. public void delete(Connection con,int id) throws SQLException,IOException {
  27. String sql="delete from user where id=?";
  28. try{
  29. st=con.prepareStatement(sql);
  30. st.setInt(1, id);
  31. st.executeUpdate();
  32. }finally{
  33. if (null!=st) {
  34. st.close();
  35. }
  36. }
  37. }
  38. public void update( Connection con,int id,String name) throws SQLException,IOException {
  39. String sql="update user set name=? where id=?";
  40. try{
  41. st=con.prepareStatement(sql);
  42. st.setString(1, name);
  43. st.setInt(2, id);
  44. st.executeUpdate();
  45. }finally{
  46. if (null!=st) {
  47. st.close();
  48. }
  49. }
  50. }
  51. public User query(Connection con,int index) throws SQLException,IOException{
  52. User user=new User();
  53. String sql="select * from user where id=?";
  54. try{
  55. st=con.prepareStatement(sql);
  56. st.setInt(1, index);
  57. rs=st.executeQuery();
  58. while (rs.next()) {
  59. user.setId(rs.getInt(1));
  60. user.setName(rs.getString(2));
  61. break;
  62. }
  63. }finally{
  64. if (null!=rs) {
  65. rs.close();
  66. }
  67. if (null!=st) {
  68. st.close();
  69. }
  70. }
  71. return user;
  72. }
  73. public List<User> queryAll(Connection con) throws SQLException,IOException {
  74. List<User> list=new ArrayList<>();
  75. String sql="select * from user";
  76. try {
  77. st=con.prepareStatement(sql);
  78. rs=st.executeQuery();
  79. while (rs.next()) {
  80. User user=new User();
  81. user.setId(rs.getInt(1));
  82. user.setName(rs.getString(2));
  83. list.add(user);
  84. }
  85. }finally{
  86. if (null!=rs) {
  87. rs.close();
  88. }
  89. if (null!=st) {
  90. st.close();
  91. }
  92. }
  93. return list;
  94. }
  95. }

2、JDBC连接的测试类

1)、TestJdbc.java:数据库测试类

  1. package cn.java.jdbc;
  2. import java.io.IOException;
  3. import java.sql.Connection;
  4. import java.sql.SQLException;
  5. import java.util.List;
  6. public class TestJdbc {
  7. public static void main(String[] args) {
  8. Connection con=null;
  9. try {
  10. con=(Connection) ConnectionFactory.getInstance().getConnection();
  11. UserDao userDao=new UserDao();
  12. //con=(Connection) ConnectionFactory2.getInstance().getConnection();
  13. if (null!=con) {
  14. System.out.println("Link JDBC SUCESS");
  15. //userDao.insert(con, "zhangsir");
  16. //userDao.delete(con, 4);
  17. //userDao.update(con, 1, "david");
  18. List<User> list=userDao.queryAll(con);
  19. for (User user : list) {
  20. System.out.println("id="+user.getId()+" name="+user.getName());
  21. }
  22. }
  23. } catch (SQLException e) {
  24. e.printStackTrace();
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }finally{
  28. if (null!=con) {
  29. try {
  30. con.close();
  31. } catch (SQLException e) {
  32. }
  33. }
  34. }
  35. }
  36. }

三、JDBC连接总结

JDBC操作的基本步骤是:

1、创建Connection对象,传入SQL查询命令字符串;

2、获取PreparedStatement对象:通过Connection对象传入SQL查询命令获取;

3、获取ResultSet:对PreparedStatement执行executeUpdate()或者executeQurey()获取;

4、依次关闭打开的对象:先后关闭ResultSet、PreparedStatement和Connection对象.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/743214
推荐阅读
相关标签
  

闽ICP备14008679号