目录
一、原始SQL查询
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 四大参数
// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
String USER = "root";
String PASS = "123456";
// 数据库对象
Connection connection;
Statement statement;
PreparedStatement preparedStatement;
ResultSet resultSet;
//查询语句
String rawSql = "select * from test";
String preparedSql = "select * from test where id = ?";
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL, USER, PASS);
statement = connection.createStatement();
resultSet = statement.executeQuery(rawSql);
print(resultSet);
preparedStatement = connection.prepareStatement(preparedSql);
preparedStatement.setInt(1, 1);
resultSet = preparedStatement.executeQuery();
print(resultSet);
}
private static void print(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
Integer id = resultSet.getInt("id");
Integer testTiny1 = resultSet.getInt("test_tiny_1");
Integer testTiny2 = resultSet.getInt("test_tiny_2");
String testSnapshot = resultSet.getString("test_snapshot");
System.out.println("id=" + id + "\ttestTiny1=" + testTiny1 + "\t testTiny2=" + testTiny2 + "\ttestSnapshot=" + testSnapshot);
}
}
二、缺点
1、数据库连接每次都要配置 (可以写成静态的)
2、每次都建立connection (可以写成线程池)
3、sql语句需要自己拼接 (这个如何改进)
4、解析ResultSet 麻烦