功能:
-
getConnection 获取连接
-
release 释放连接
源码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author Dotions 2016年1月4日 下午4:18:32
*/
public class MysqlDBUtils {
private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
private static final String URL_TEMPLATE = "jdbc:mysql://%s/?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false";
public static Connection getConnection(String host, String username, String password) throws SQLException {
Connection conn = null;
try {
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(String.format(URL_TEMPLATE, host), username, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if (st != null) {
try {
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
测试:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Wang Yunfei 2016年4月26日 下午3:03:41
*/
public class MysqlDBUtilsTest {
public static void main(String[] args) {
// create sql
String sql = SqlGenerator.getUsers();
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
// get connection
conn = MysqlDBUtils.getConnection("127.0.0.1:3306", "root", "root");
// get statement
pstm = conn.prepareStatement(sql);
// get resultSet
rs = pstm.executeQuery();
// do something
while (rs.next()) {
UserProp user = new UserProp();
user.setName(rs.getString("uname"));
user.setAge(rs.getInt("uage"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
MysqlDBUtils.release(conn, pstm, rs);
}
}
}