Java:jdbc Too many connections

一般来说,我们使用jdbc都可以封装好类。
但是可能会出现Data source rejected establishment of connection, message from server: "Too many connections"
异常。这是因为我们没有关闭数据库的连接,导致数据库连接过多。

下面封装好的MySql类:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MySql {
	static String ip = "ip地址";
	static String port = "3306";
	static String databaseName = "数据库名字";
	static String encode = "useUnicode=true&characterEncoding=utf-8"; // 设置数据库连接为字符集较大的utf-8
	static String username = "连接数据库的账号";
	static String password = "连接数据库的密码";
	static Connection connection; // 与数据库的连接

	public static Connection getConn() { // 获取与数据库的连接
		String url = "jdbc:mysql://" + ip + ":" + port + "/" + databaseName + "?" + encode; // 连接数据库的路径
		try {
			Class.forName("com.mysql.jdbc.Driver"); // 加载驱动
			connection = DriverManager.getConnection(url, username, password); // 创建和数据库的连接
			return connection;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static PreparedStatement getPreparedStatement(String sql) { // 获取SQL操作数据库的准备
		try {
			return MySql.getConn().prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static ResultSet select(String sql, Object[] objects) {
		try {
			PreparedStatement preparedStatement = MySql.getPreparedStatement(sql);
			for(int i = 0; i < objects.length; i ++)
				preparedStatement.setObject(i+1, objects[i]);
			return preparedStatement.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static int insert(String sql, Object[] objects) {
		try {
			PreparedStatement preparedStatement = MySql.getPreparedStatement(sql);
			for(int i = 0; i < objects.length; i ++)
				preparedStatement.setObject(i+1, objects[i]);
			return preparedStatement.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public static int delete(String sql, Object[] objects) {
		try {
			PreparedStatement preparedStatement = MySql.getPreparedStatement(sql);
			for(int i = 0; i < objects.length; i ++)
				preparedStatement.setObject(i+1, objects[i]);
			return preparedStatement.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public static int update(String sql, Object[] objects) {
		try {
			PreparedStatement preparedStatement = MySql.getPreparedStatement(sql);
			for(int i = 0; i < objects.length; i ++)
				preparedStatement.setObject(i+1, objects[i]);
			return preparedStatement.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public static void close() {
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/new_Aiden/article/details/50971016