欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java--jdbc

程序员文章站 2022-05-02 14:00:07
...

1.jdbc的测试代码

maven依赖

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
import java.sql.*;
import java.util.UUID;

public class JdbcTest {
    public static void main(String[] args){
        insertData();
    }
    public static Connection getConnection(){
        try {
            //加载驱动到jvm
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:mysql://localhost:3306/mybatisdb?characterEncoding=UTF-8";
        String username = "root";
        String password = "root";
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void createTable(String sql){
        Connection conn = getConnection();
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            if(null!=ps) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(null!=conn) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void insertData(){
        Connection conn = getConnection();
        String sql = "insert into user(id,name,password) values(?,?,?)";
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, UUID.randomUUID().toString());
            ps.setString(2, "fcc");
            ps.setString(3, "password");
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(null!=ps) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(null!=conn) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void selectData(){
        Connection conn = getConnection();
        String sql = "select * from user";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                System.out.println(rs.getString(1));//1代表数据库中表的列数
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(null!=rs) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(null!=ps) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(null!=conn) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2.源码浅析

try {
//加载驱动到jvm
Class.forName(“com.mysql.jdbc.Driver”);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

package com.mysql.jdbc;

import java.sql.SQLException;

/**
 1. The Java SQL framework allows for multiple database drivers. Each driver should supply a class that implements the Driver interface
 2. //Java SQL框架允许多个数据库驱动程序。每个驱动程序应该提供一个实现驱动程序接口的类
 3. <p>
 4. The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to
 5. connect to the target URL.
 6. //DriverManager会尝试加载尽可能多的驱动程序,然后对于任何给定的连接请求,它会要求每个驱动程序依次尝试
连接到目标URL。
 7. <p>
 8. It is strongly recommended that each Driver class should be small and standalone so that the Driver class can be loaded and queried without bringing in vast
 9. quantities of supporting code.
 10. 
 11. <p>
 12. When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a
 13. driver by doing Class.forName("foo.bah.Driver")
 */
 //当一个驱动类被加载时,它应该创建一个自己的实例,并将其注册到驱动管理器。这意味着用户可以通过Class.forName("foo.ba . driver ")来加载并注册
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    //
    // Register ourselves with the DriverManager
    //
    static {
        try {
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }

    /**
     * Construct a new driver and register it with DriverManager
     * 
     * @throws SQLException
     *             if a database error occurs.
     */
    public Driver() throws SQLException {
        // Required for Class.forName().newInstance()
    }
}
  1. 注册驱动,实际就是放到
    private final static CopyOnWriteArrayList registeredDrivers = new CopyOnWriteArrayList<>();
    这个list里
public static synchronized void registerDriver(java.sql.Driver driver,
            DriverAction da)
        throws SQLException {

        /* Register the driver if it has not already been added to our list */
        if(driver != null) {
            registeredDrivers.addIfAbsent(new DriverInfo(driver, da));
        } else {
            // This is for compatibility with the original DriverManager
            throw new NullPointerException();
        }

        println("registerDriver: " + driver);

    }

3.DriverManager.getConnection()。最终返回com.mysql.jdbc.ConnectionImpl的实例
java--jdbc

  1. 源码太长了,最终进入到MysqlIo类里面
    调用final ResultSetInternalMethods sqlQueryDirect(StatementImpl callingStatement, String query, String characterEncoding, Buffer queryPacket, int maxRows,
    int resultSetType, int resultSetConcurrency, boolean streamResults, String catalog, Field[] cachedMetadata) throws Exception {
    把东西查到内存里
相关标签: java SE

推荐阅读