JDBC一般步骤
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC", username, password);
String sql = "select * from tb_test";
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet rs = statement.executeQuery(sql);
while (rs.next())
System.out.println(rs.getInt(1) + "--" + rs.getString(2));
rs.close();
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
JDBC工具类
package com.utils;
import java.sql.*;
public class JdbcUtil {
static {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
public static Connection getConnection(String url, String username, String password) throws SQLException {
return DriverManager.getConnection(url, username, password);
}
public static void close(Connection conn, Statement ps, ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}