简单的jdbc测试程序

 
  

本程序使用maven程序搭建

pom文件依赖如下:


  
    junit
    junit
    4.11
    test
  
  
  
    org.clojure
    java.jdbc
    0.6.0
  
  
  
    mysql
    mysql-connector-java
    6.0.6
  

这些依赖都可以在下面这个网站上找到:

https://mvnrepository.com/

import org.junit.Test;

import java.sql.*;


public class test1 {

    private static String jdbcName = "com.mysql.cj.jdbc.Driver";
    private static String dbUrl = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useUnicode=true&" +
            "sessionVariables=storage_engine%3DInnoDB&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    private static String dbUserNmae = "root";
    private static String dbPassword = "root";

    @Test
    public void SimpleTest() throws SQLException {

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        //1.加载数据库驱动
        try {
            Class.forName(jdbcName);
            System.out.println("数据库驱动加载成功");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //2.创建连接
        try {
            connection = DriverManager.getConnection(dbUrl,dbUserNmae,dbPassword);
            System.out.println("数据库连接创建成功");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //3.创建数据库会话
        try {
            statement = connection.createStatement();
            System.out.println("数据库会话创建成功");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //4.创建sql语句
        String sql = "select u_id, u_name, u_password from t_user";
        //5.执行sql语句
        try {
            resultSet = statement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //6.处理结果集
        while(resultSet.next()){
            int id = resultSet.getInt("u_id");
            String name = resultSet.getString("u_name");
            String password = resultSet.getString("u_password");

            System.out.println("id = "+id+",name="+name+",password = "+password);
        }
        //7.关闭资源

        if (resultSet != null){
            resultSet.close();
        }
        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

你可能感兴趣的:(java,mysql)