package com.rupeng.test1;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtils
{
private static final String drivername;
private static final String dburl;
private static final String dbusername;
private static final String dbpassword;
static
{
InputStream inStream=null;
try
{
inStream=JdbcUtils.class.getResourceAsStream("config.properties");
Properties prop=new Properties();
prop.load(inStream);
drivername=prop.getProperty("drivername");//"com.mysql.jdbc.Driver";
dburl=prop.getProperty("dburl");
dbusername=prop.getProperty( "dbusername");
dbpassword=prop.getProperty("dbpassword");
} catch (IOException e)
{
throw new RuntimeException("加載config.properties失敗",e);
}
finally
{
if(inStream!=null)
{
try
{
inStream.close();
}catch(IOException e)
{
}
}
}
try
{
Class.forName(drivername);
} catch (ClassNotFoundException e)
{
throw new RuntimeException("加載musql jdbc失敗",e);
}
}
public static Connection createConnection() throws SQLException//不知道如何處理
{
return DriverManager.getConnection(dburl,dbusername,dbpassword);
}
public static int executeUpdate(String sql,Object...parameters) throws SQLException
{
Connection conn=null;
try
{
conn=createConnection();
return executeUpdate(conn,sql,parameters);
}finally
{
closeQuietly(conn);
}
}
public static int executeUpdate(Connection conn,String sql,Object...parameters) throws SQLException
{
PreparedStatement ps=null;
try
{
ps=conn.prepareStatement(sql);
for(int i=0;i<parameters.length;i++)
{
ps.setObject(i+1, parameters[i]);
}
return ps.executeUpdate();
}
/**
* catch(SQLExcption e)
* {
* System.out.println("xhicingchu錯");這是吃異常因爲我們不知道如何vchuli
* }
*/
finally
{
closeQuietly(ps);//Connection conn 是調用的,不能關閉
}
}
public static ResultSet executeQuery(String sql,Object...parameters) throws SQLException
{
Connection conn=createConnection();//不涉及到關閉資源
return executeQuery(conn,sql,parameters);
}
public static ResultSet executeQuery(Connection conn,String sql,Object...parameters) throws SQLException
{
PreparedStatement ps=conn.prepareStatement(sql);
for(int i=0;i<parameters.length;i++)
{
ps.setObject(i+1, parameters[i]);
}
return ps.executeQuery();
//PreparedStatement 關掉話 ResultSet用不了
//由調用者關閉
}
public static void closeQuietly(Statement stmt)
{
if(stmt!=null)
{
try
{
stmt.close();
}catch(SQLException e)
{
}
}
}
public static void closeQuietly(Connection conn)
{
if(conn!=null)
{
try
{
conn.close();
}catch(SQLException e)
{
}
}
}
static void closeQuietly(ResultSet rs)
{
if(rs!=null)
{
try
{
rs.close();
}catch(SQLException e)
{
}
}
}
}