第一步:开启Mysql服务
第二步:创建数据库和表(User表)
第三步:使用JDBC接口创建连接
使用Maven创建项目,导入mysql.driver和junit。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Taojj</groupId> <artifactId>DatabaseLearning</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>
编写测试代码。
import com.mysql.cj.jdbc.Driver; import org.junit.Test; import java.sql.*; public class JDBCTest { @Test public void ConnectMysql() throws SQLException { String url = "jdbc:mysql://localhost:3306/mybatabase"; String user = "root"; String password = "spide3428man"; // 注册驱动 DriverManager.registerDriver(new Driver()); // 建立连接 Connection connection = DriverManager.getConnection(url, user, password); // 创建语句 Statement statement = connection.createStatement(); // 执行查询 ResultSet resultSet = statement.executeQuery("select * from user"); // 处理结果 while (resultSet.next()) { System.out.println("id: " + resultSet.getObject(1) + "; name: " + resultSet.getObject(2)); } // 释放资源 resultSet.close(); statement.close(); connection.close(); } }
返回结果:
碰到一个问题,执行代码的时候碰到:
The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone.
解决方案:重新设置时区。