idea中添加mysql-connector依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
代码实现
public class ConMysql {
//url后面的部分是为了解决字符编码格式和时区不一致的问题
private static String URL = "jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
private static Queue<Connection> connectionList = new LinkedList<>();
//连接池在构造方法中初始化,new对象的时候执行,完成初始化
public ConMysql() {
for(int i = 0; i < 10; i++) {
try {
//加载数据库驱动的方式有Class.forName("com.mysql.cj.jdbc.Driver")、DriverManager.registerDriver(new com.mysql.jdbc.Driver())、System.setProperty("jdbc.driver","com.mysql.jdbc.Driver");
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, "username", "password");
connectionList.offer(conn);
} catch(ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
//返回并删除队列头部的连接对象
public Connection getConnection() {
return connectionList.poll();
}
public static void main(String[] args) {
ConMysql conMysql = new ConMysql();
try {
Connection conn = conMysql.getConnection();
//使用PreparedStatement的set方法可以避免sql注入,原理是使用了占位符?,将输入的参数用单引号括起来,避免where column_name = xxx or 1=1可以恶意查询。
PreparedStatement statement = conn.prepareStatement("select * from table_name where column_name = ?");
statement.setString(1, "column_value");
ResultSet rs = statement.executeQuery();
while(rs.next()) {
System.out.println(rs.getString(1));
}
//关闭连接,释放资源,数据库连接、IO连接、网络连接不关闭可能会导致内存泄漏
rs.close();
statement.close();
conn.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
}