import java.sql.*;
public class Demo1 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获得链接
String userName = "root";
String password = "root";
String url = "jdbc:mysql://localhost:3306/yhp2?serverTimezone=UTC";
connection = DriverManager.getConnection(url,userName,password);
//3.定义sql,创建状态通道(进行sql语句的发送)
statement = connection.createStatement();
变动区域
resultSet = statement.executeQuery("select * from emp1"); //executeQuery(sql) 执行查询
//4.取出结果集信息
while(resultSet.next()){ //判断是否有下一条数据
//取出数据: resultSet.getXXX("列名") xxx表示数据类型
System.out.println("姓名:"+resultSet.getString("ename")+"工资:"+
resultSet.getDouble("sal")+",雇佣日期:"+resultSet.getDate("hiredate"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
//5.关闭资源
if(resultSet !=null){
resultSet.close();
}
if(statement !=null){
statement.close();
}
if( connection !=null){
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
数据库yhp2
emp1表
执行结果显示: