贴代码:
package org.example;
import java.sql.*;
import java.util.ResourceBundle;
public class App {
public static void main(String[] args) {
Statement statement=null;
Connection conn=null;
ResultSet rs=null;
//读取配置文件
ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
String driver=bundle.getString("driver");
String url=bundle.getString("url");
String user=bundle.getString("user");
String password=bundle.getString("password");
try{
//注册驱动
Class.forName(driver);
//获取连接对象
conn=DriverManager.getConnection(url,user,password);
//获取数据库操作对象
statement=conn.createStatement();
//执行SQL
rs=statement.executeQuery("select * from tb_users");//增删改用statement.executeUpdate("");
//处理查询结果集
while (rs.next()){
System.out.println(rs.getString(1)+rs.getString(2)+rs.getString(3));
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e){
e.printStackTrace();
}finally {
//释放资源,从小到大
try{
if (rs!=null)
rs.close();
}catch (SQLException e){
e.printStackTrace();
}
try{
if (statement!=null)
statement.close();
}catch (SQLException e){
e.printStackTrace();
}
try{
if (conn!=null)
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
配置文件:(jdbc.properties)
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test_db
user=root
password=root