JAva接続データベースツールクラスバックアップ
4538 ワード
package com.util;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
*
* @author songfw
* 2014.10.13
*/
public class DBUtil{
private static final String DBDRIVER="com.mysql.jdbc.Driver";//
private static final String DBNAME="test";//
private static final String DBURL="jdbc:mysql://localhost:3306/"+DBNAME;// URL
private static final String DBUSER="root";//
private static final String DBPASSWORD="1234";//
private static Connection conn=null;
private static PreparedStatement ps=null;
private static ResultSet rs=null;
//
public static Connection getConnection(){
try{
Class.forName(DBDRIVER);//
conn=DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);//
}catch(ClassNotFoundException e){//
e.printStackTrace();
}catch(SQLException e){// SQL
e.printStackTrace();
}
return conn;
}
//
public ResultSet select(String sql)throws Exception{
try{
conn=getConnection();
ps=conn.prepareStatement(sql);
rs=ps.executeQuery(sql);
return rs;
}catch(SQLException sqle){
throw new SQLException("select data Exception: "+sqle.getMessage());
}catch(Exception e){
throw new Exception("System error: "+e.getMessage());
}
}
//
public int insert(String sql)throws Exception{
int num=0;//
try{
conn=getConnection();
ps=conn.prepareStatement(sql);
num=ps.executeUpdate();
}catch(SQLException sqle){
throw new SQLException("insert data Exception: "+sqle.getMessage());
}finally{
try{
if(ps!=null){
ps.close();
}
}catch(Exception e){
throw new Exception("ps close exception: "+e.getMessage());
}
try{
if(conn!=null){
conn.close();
}
}catch(Exception e){
throw new Exception("conn close exception: "+e.getMessage());
}
}
return num;
}
//
public int delete(String sql)throws Exception{
int num=0;//
try{
conn=getConnection();
ps=conn.prepareStatement(sql);
num=ps.executeUpdate();
}catch(SQLException sqle){
throw new SQLException("delete data Exception: "+sqle.getMessage());
}finally{
try{
if(ps!=null){
ps.close();
}
}catch(Exception e){
throw new Exception("ps close Exception: "+e.getMessage());
}
try{
if(conn!=null){
conn.close();
}
}catch(Exception e){
throw new Exception("conn close Exception: "+e.getMessage());
}
}
return num;
}
//
public int update(String sql)throws Exception{
int num=0;//
try{
conn=getConnection();
ps=conn.prepareStatement(sql);
num=ps.executeUpdate();
}catch(SQLException sqle){
throw new SQLException("update data Exception: "+sqle.getMessage());
}finally{
try{
if(ps!=null){
ps.close();
}
}catch(Exception e){
throw new Exception("ps close Exception: "+e.getMessage());
}
try{
if(conn!=null){
conn.close();
}
}catch(Exception e){
throw new Exception("conn close Excepiton: "+e.getMessage());
}
}
return num;
}
}