java 连接数据库

java环境是:

jdk1.8    java version "1.8.0_171"

1.安装mysql的jar

下载地址:http://dev.mysql.com/downloads/connector/j/

我下载的时候,一直打不开,开了蓝灯很快就打开了。蓝灯有时候不可以用

jar支持的版本:

 

下载完成后,需要eclipse加入jar包:即可把jar包放进项目里

 

2.创建数据库:

CREATE TABLE `student` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;

3.编写java代码

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MysqlDemo {

    final static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    final static String DB_URL = "jdbc:mysql://localhost:3306/mv?serverTimezone=UTC";

    final static String USER = "root";
    final static String PASS = "root";

    public static void main(String[] args)
            throws ClassNotFoundException, SQLException {
        Connection conn = null;
        Statement stmt = null;

        Class.forName(JDBC_DRIVER);
        System.out.println("连接数据库...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        // 执行查询
        stmt = conn.createStatement();
        String sql = "select * from student";
        ResultSet rs = stmt.executeQuery(sql);

        // 展开结果集
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");

            System.out.println("ID:" + id);
            System.out.println("name:" + name);
            System.out.println("age:" + age);
        }
    }

}

执行结果:成功

 

4.遇到的问题:

4.1 The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone

解决:

jdbc:mysql://localhost:3306/mv?serverTimezone=UTC

4.2 Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary

解决:原来的driver有修改

final static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";

 

posted @ 2018-05-17 17:31  myvic  阅读(218)  评论(0编辑  收藏  举报