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();
}
}
推荐阅读
-
配置 SQL Server 2005 以允许远程连接的方法
-
将子查询改造成join连接查询
-
数据库-PHP连接到服务器的问题
-
myeclipse连接mysql数据库错误问题解决(搞了好久才发现是这个问
-
mybatis-MYSQL+MYBATIS连接池 java.io.eof
-
sqlserver2005-PHP通过ODBC连接SQLSERVER2005 查询不了中文
-
airpods怎么连接安卓手机 airpods可以在安卓上改名吗
-
Mssql 2000通过本地客户端远程注册、连接服务器[图]_MySQL
-
PHP连接MySQL数据的操作要点_PHP教程
-
ASP连接 MSSQL的错误: 拒绝访问_MySQL