使用JDBC连接mysql详细步骤以及增删改数据点击:https://blog.csdn.net/qq_39588003/article/details/105498473
package com.health.jdbc.查;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.cj.protocol.Resultset;
public class JdbcSelect {
public static void main(String[] args) throws Exception {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.注册驱动(mysql8可省略)
Class.forName("com.mysql.cj.jdbc.Driver");
//2.定义sql
String sql = "select * from books";
//3.获取Connection对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?serverTimezone=Asia/Shanghai","用户名","密码");
//4.获取执行sql的对象 Statement
stmt = conn.createStatement();
//5.执行sql
rs = stmt.executeQuery(sql);
//6.处理结果
while(rs.next()) {
//循环判断游标是否在最后一行末尾
//根据表的各个字段名(或序号)获取数据
int id = rs.getInt("id");
String name = rs.getString(2);
String price = rs.getString("price");
String author = rs.getString(4);
System.out.println(id+"---"+name+"---"+price+"---"+author);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
//7.释放资源
//避免空指针异常
if(rs!=null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(stmt!=null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
查询结果:
数据库books表: