欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MySQL8连接JDBC

程序员文章站 2022-05-30 13:21:26
...

资源参考

第一步:先在mysql里新建数据库与表

CREATE DATABASE jdbc_demo CHARACTER SET utf8 COLLATE utf8_general_ci;

USE jdbc_demo;

CREATE TABLE `users`(
	id INT PRIMARY KEY,
	NAME VARCHAR(40),
	PASSWORD VARCHAR(40),
	email VARCHAR(60),
	birthday DATE
);

INSERT INTO `users`(id,NAME,PASSWORD,email,birthday)
VALUES(1,'zhansan','123456','[email protected]','1980-12-04'),
(2,'lisi','123456','[email protected]','1981-12-04'),
(3,'wangwu','123456','[email protected]','1979-12-04')

第二步:在idea里新建一个java工程,并添加mysql依赖
(推荐用maven)

	<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.23</version>
    </dependency>

第三步:输入代码
注意:mysql8的语法与之前版本的有所不同

package org.example;

import java.sql.*;

/**
 * @author Riter
 */
public class Test {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //2.用户信息和url
        String url = "jdbc:mysql://localhost:3306/jdbc_demo?useSSL = false & serverTimezone=Asia/Shanghai ";
        String username = "root";
        String password = "root";

        //3.连接成功,数据库对象
        Connection connection = DriverManager.getConnection(url, username, password);

        //4.执行SQL的对象
        Statement statement = connection.createStatement();

        //5.执行SQL对象去执行SQL,可能存在结果,查看返回结果
        String sql = "Select * From users";
        ResultSet resultSet = statement.executeQuery(sql);
        while(resultSet.next()){
            System.out.println("id = "+resultSet.getObject("id"));
            System.out.println("name = "+resultSet.getObject("name"));
            System.out.println("pwd = "+resultSet.getObject("password"));
            System.out.println("email = "+resultSet.getObject("email"));
            System.out.println("birth = "+resultSet.getObject("birthday"));
        }

        //6.释放连接
        resultSet.close();
        statement.close();
        connection.close();
    }
}

相关标签: 学习笔记

上一篇: fs文件模块

下一篇: 哪个碧池的