您的位置:首页 > 数据库 > MySQL

jdbc连接Mysql方法封装

2014-08-11 23:30 351 查看
package com.shopping.util;

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

public class DB {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

public DB(){
}

public static Connection getConn(){
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bbs?user=root");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

public static Statement getStmt(Connection conn){
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}

public static PreparedStatement getPrepStmt(Connection conn,String sql){
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return pstmt;
}

public static ResultSet getRset(Statement stmt,String sql){
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}

public static ResultSet getPrepRset(PreparedStatement pstmt){
ResultSet rs = null;
try {
rs = pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}

public static void close(Connection conn){
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}

public static void close(PreparedStatement pstmt){
if(pstmt != null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
pstmt = null;
}
}
public static void close(ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: