JDBC相关配置和操作

获取数据库连接的几种方式

ps.数据库URL : String url = "jdbc:mysql://localhost:3306/dailytext?useSSL=false&serverTimezone=UTC"

​ MySQL5.0-->driverClass="com.mysql.jdbc.Driver";

​ MySQL8.0-->driverClass="com.mysql.cj.jdbc.Driver";

通过Driver实例获取

//创建Driver对象
Driver driver = new Driver();
//数据库URL
String url = "jdbc:mysql://localhost:3306/dailytext?useSSL=false&serverTimezone=UTC";
//Properties存放用户名和密码
Properties prop = new Properties();
prop.setProperty("user", "user1");
prop.setProperty("password", "102850");
//调用connect(),传入url和prop
Connection connect = driver.connect(url, prop);
//获得连接
System.out.println(connect);

通过DriverManager获取

public class Jdbc8Test01 {

    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/dailytext?useSSL=false&serverTimezone=UTC";

    // 数据库的用户名与密码
    static final String USER = "root";
    static final String PASS = "102850";

    public static void main(String[] args) {

        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);

            // 展开结果集数据库
            while (rs.next()) {
                // 通过字段检索
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String url = rs.getString("url");

                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 站点名称: " + name);
                System.out.print(", 站点 URL: " + url);
                System.out.print("
");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        }// 处理 Class.forName 错误
        finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }// 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

从配置文件获取信息

  1. 配置文件内容

    user=root
    password=102850
    url=jdbc:mysql://localhost:3306/dailytext?useSSL=false&serverTimezone=UTC
    #MySQL8.0以上版本 JDBC 驱动名
    driverClass=com.mysql.cj.jdbc.Driver
    #MySQL8.0以下版本 JDBC 驱动名
    #driverClass=com.mysql.jdbc.Driver
    
    1. 实例代码
    //获取输入流(两种方法)
    InputStream is = Jtest01.class.getClassLoader().getResourceAsStream("jdbc.properties");
    //main方法中文件路径为Project下
    FileInputStream fis = new FileInputStream("TEST02\src\jdbc.properties");
    
    Properties prop = new Properties();
    prop.load(fis);
    
    //获取配置信息
    String user = prop.getProperty("user");
    String password = prop.getProperty("password");
    String url = prop.getProperty("url");
    String driverClass = prop.getProperty("driverClass");
    
    //注册驱动
    Class.forName(driverClass);
    
    //获得Connection对象,建立与数据库的连接
    Connection connection1 = DriverManager.getConnection(url, user, password);
    Connection connection2 = DriverManager.getConnection(url, prop);
    
    System.out.println(connection1);
    System.out.println(connection2);
    
    

druid数据库连接池

配置文件druid.proterties

url=jdbc:mysql://localhost:3306/dailytext?serverTimezone=UTC
username=user1
password=102850
driverClassName=com.mysql.cj.jdbc.Driver
initialSiize=10
maxActive=10

代码实现

//从数据库连接池获取连接
Properties prop = new Properties();

//ClassLoader.getSystemClassLoader().getResourceAsStream("String pathName")
// 此种方式读取文件位置默认为src目录下(在main方法和在@Test方法中路径一样)
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("Resource\druid.properties");

//FileInputStream("String pathName")
// 在main方法中,此种方式读取文件位置默认为Project目录下
// 在@Test方法中,此种方式读取文件位置默认为Module目录下
// FileInputStream is = new FileInputStream("JDBC\src\Resource\druid.properties");
prop.load(is);
DataSource source = DruidDataSourceFactory.createDataSource(prop);
Connection conn = source.getConnection();
System.out.println(conn);

PreparedStatement对比Statement的优点

(好处是基于PreparedStatement的预编译SQL语句功能)

  1. 解决SQL语句拼串的问题
  2. 解决SQL注入问题
  3. 实现对Blob类型的字段操作
  4. 提高批量操作时的效率

对数据库执行操作

步骤

1.创建文件输入流,从配置文件读取配置信息,
    ①.文件输入流位于main方法中时文件读取位置在Project目录下
    ②.文件输入流位于@Test方法中时文件读取位置在Module目录下
2.传入文件流
3.读取配置信息
4.加载JDBC驱动
5.通过DriverManager创建connection对象,获取数据库连接
6.编写SQL语句,使用占位符
7.创建statement(PreparedStatement)对象,传入SQL语句进行预编译
8.填充占位符
9.执行SQL操作
10.关闭资源

示例代码

public static void main(String[] args) {

    FileInputStream fis = null;
    Connection conn = null;
    PreparedStatement pst = null;

    try {
        //获取文件输入流(main方法中文件位置在当前Project下)
        fis = new FileInputStream("JDBC\jdbc.properties");

        //传入文件流
        Properties prop = new Properties();
        prop.load(fis);

        //读取配置信息
        String url = prop.getProperty("url");
        String driverClass = prop.getProperty("driverClass");
        System.out.println(url);
        System.out.println(driverClass);

        //加载JDBC驱动
        Class.forName(driverClass);

        //获取数据库连接
        conn = DriverManager.getConnection(url, prop);
        System.out.println(conn);

        //预编译SQL语句
        //String sql = "INSERT INTO person(`name`,`age`,`gender`,`birthday`)VALUES(?,?,?,?)";
        String sql = "update person set `name`=? where `name`=?";
        pst = conn.prepareStatement(sql);

        //填充占位符
        pst.setString(1, "Eclipse");
        pst.setString(2, "Idea");

        //执行操作(Insert;Update;Delete)
        boolean execute = pst.execute();
        System.out.println(execute);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //关闭连接
        try {
            if (pst!=null)
                pst.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (conn!=null)
                conn.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (fis!=null)
                fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
原文地址:https://www.cnblogs.com/shmebluk/p/13099467.html