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)
{
}
}
}
}