JDBC基础

JDBC基础

菜鸟教程: http://www.runoob.com/java/java-mysql-connect.html

环境配置

  1. MySQL安装在CentOS 7的服务器上http://www.cnblogs.com/yueshangzuo/p/8652890.html
  2. 下载连接MySQL的驱动包https://dev.mysql.com/downloads/connector/j/
  3. 解压将jar导入IDEA工程(选择Project structure -> Library,导入)

连接

package com.neptune.mysql;

import java.sql.*;

public class Demo {
    private static final String DRIVER_URL="com.mysql.jdbc.Driver";
    private static final String DB_URL="jdbc:mysql://****:3306/TEST_DB?useSSL=false";
    private static final String USER="root";
    private static final String PASSWD="****";

    public static void main(String[] args) {
        Connection connection=null;
        Statement statement=null;

        try{
            // 注册驱动
            Class.forName(DRIVER_URL);

            // 建立连接
            connection=DriverManager.getConnection(DB_URL,USER,PASSWD);
            System.out.println("connection success.");

            // 查询
            statement=connection.createStatement();
            String sql="select * from Test"; //id title author date price degree
            ResultSet resultSet=statement.executeQuery(sql);

            // print
            System.out.printf("%-5s%-20s%-20s%-20s%-10s%-10s\n","id","title","author","date","price","degree");
            while(resultSet.next()){
                Long id=resultSet.getLong("id");
                String title=resultSet.getString("title");
                String author=resultSet.getString("author");
                Date date=resultSet.getDate("date");
                Double price=resultSet.getDouble("price");
                String degree=resultSet.getString("degree");

                System.out.printf("%-5d%-20s%-20s%-20s%-10.2f%-10s\n",id,title,author,date,price,degree);
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            try{
                if(statement!=null) statement.close();
            }catch (Exception e){
                e.printStackTrace();
            }

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

  • 报错: java.sql.SQLException: null, message from server: "Host '*** is not allowed to connect to this MySQL server"

登陆MySQL修改

use mysql
show tables;
select host from user;
update user set host='%' when user='root';

重启即可

sudo mysqld service restart
  • warn: ssl认证

在url里面添加 ?useSSL=false

posted @ 2018-04-12 16:30  Neptune15  阅读(141)  评论(0编辑  收藏  举报