码迷,mamicode.com
首页 > 数据库 > 详细

java 连接数据库

时间:2018-05-17 18:23:57      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:local   查询   this   sele   分享   res   技术   http   connector   

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";

 

java 连接数据库

标签:local   查询   this   sele   分享   res   技术   http   connector   

原文地址:https://www.cnblogs.com/myvic/p/9052214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!