/*
1加载驱动
2连接数据库
3向数据库发送sql的对象Statement : CRUD
4编写sql
5执行查询sql ,返回一个resultSet : 结果集
6关闭连接,释放资源(一定要做)先开后关
*/
/*
首先添加数据库依赖
<!--mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
*/
package jdbc;
import java.sql.*;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=PRC";
String username = "root";
String password = "";
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库
Connection connection = DriverManager.getConnection(url,username,password);
//向数据库发送sql的对象Statement : CRUD
Statement statement = connection.createStatement();
//编写sql
String sql = "select * from users";
//执行查询sql ,返回一个resultSet : 结果集
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
System.out.println("email="+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
}
//关闭连接,释放资源(一定要做)先开后关
rs.close();
statement.close();
connection.close();
}
}