<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
import java.sql.*;
public class JdbcDemo {
private static final String URL = "jdbc:mysql://localhost:3306/test?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false";
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
Connection conn = JdbcDemo.getConnection();
PreparedStatement pst = conn.prepareStatement("SELECT * FROM tb_area ORDER BY id ASC LIMIT 5;");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getString(5));
}
JdbcDemo.closeConnection(conn, pst, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
public static void closeConnection(Connection conn, PreparedStatement pst, ResultSet rs) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}