package top.enjoy.test.jdbc;
import java.sql.*;
import java.util.List;
public class Demo1 {
public static void main(String[] args) throws Exception {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//通过驱动管理获取数据库连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8","root","root");
//定义sql
String sql="select * from stu";
//建立Statement对象
PreparedStatement preparedStatement1 = connection.prepareStatement(sql);
//向数据库打出sql执行查询 ,查询出结果集
resultSet = preparedStatement1.executeQuery();
//遍历查询结果
while (resultSet.next()){
System.out.printf("id:"+resultSet.getString("id")+" 姓名:"+resultSet.getString("name")+" 年龄:"+resultSet.getString("age"));
}
}catch (ClassNotFoundException e){
e.printStackTrace();
}finally {
//释放资源
if (resultSet != null){
try {
resultSet.close();
}catch (Exception e){
e.printStackTrace();
}
}
///------------------------
if (preparedStatement != null){
try {
preparedStatement.close();
}catch (Exception e){
e.printStackTrace();
}
}
///-------------------------
if (connection != null){
try {
connection.close();
}catch (SQLException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
后面别忘了引jar包
mysql-connector-java-8.0.15.jar