c mysql封装 jdbc_彻底封装JDBC操作MySQL的连接。
只需3步。
1、導入mysql的jar包。
略
2、封裝配置文件db.properties
driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql:///databaseName?useUnicode=true&characterEncoding=utf8
user = root
password = 123
把數(shù)據(jù)庫驅(qū)動和一些數(shù)據(jù)庫參數(shù)封裝到配置文件,做到隨時更換數(shù)據(jù)庫。
3、封裝連接代碼
/**
* Created by youxuan on 2017/1/15 0015.
* JDBC工具類
*/
public class JDBCUtil {
private static final String driverClass;
private static final String url;
private static final String user;
private static final String password;
static {
try {
InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties pr = new Properties();
pr.load(in);
driverClass = pr.getProperty("driverClass");
url = pr.getProperty("url");
user = pr.getProperty("user");
password = pr.getProperty("password");
Class.forName(driverClass);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
/**
*清理數(shù)據(jù)庫資源
* @param rs
* @param stat
* @param conn
*/
public static void release(ResultSet rs, Statement stat,Connection conn){
try {
if (rs != null) {
rs.close();
}
rs = null;
if(stat != null){
stat.close();
}
stat = null;
if(conn!=null){
conn.close();
}
conn = null;
}catch (Exception e){
e.printStackTrace();
}
}
}
4、連接測試
public void text1(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JDBCUtil.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(" select * from user ");
while(rs.next()){
.......
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JDBCUtil.release(rs, stmt, conn); //關(guān)閉數(shù)據(jù)庫資源
}
}
總結(jié)
以上是生活随笔為你收集整理的c mysql封装 jdbc_彻底封装JDBC操作MySQL的连接。的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql -u -p -d_mysql
- 下一篇: mysql二进制日志被删除无法启动_my