ection conn = null;
PreparedStatement prepareStatement = null;
ResultSet rs = null;
FileOutputStream fos = null;
InputStream is = null;
try
{
conn = getConn();
// 事物处理前,取消Connection的默认提交行为
conn.setAutoCommit(false);
prepareStatement = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
{
prepareStatement.setObject(i + 1, args[i]);
}
rs = prepareStatement.executeQuery();
if (rs.next())
{
BLOB blob = (BLOB)rs.getBlob(1);
is = blob.getBinaryStream();
fos = new FileOutputStream(new File("test.png"));
byte[] b = new byte[1024];
int len;
while (-1 != (len = is.read(b)))
{
fos.write(b, 0, len);
}
fos.flush();
}
// 事物处理:如果事物处理成功则提交事物
conn.commit();
}
catch (Exception e)
{
e.printStackTrace();
try
{
// 事物处理:如果出现异常 则在catch块中回滚事物
conn.rollback();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
finally
{
if (null != is)
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (null != fos)
{
try
{
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
releaseSource(prepareStatement, conn, rs);
}
}
/**
* <一句话功能简述> 连接数据库 <功能详细描述>
*
* @return
* @throws Exception
* @see [类、类#方法、类#成员]
*/
public Connection getConn()
throws Exception
{
String dirverName = null;
String jdbcUrl = null;
String user = null;
String password = null;
Properties propertoes = new Properties();
InputStream is = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
propertoes.load(is);
dirverName = propertoes.getProperty("driver");
jdbcUrl = propertoes.getProperty("jdbcURL");
user = propertoes.getProperty("user");
password = propertoes.getProperty("password");
Class.forName(dirverName);
// 通过DriverManager的getConnection获取数据库连接
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
return connection;
}
/**
* <一句话功能简述>释放数据库资源 <功能详细描述>
*
* @param statement
* @param conn
* @param resultSet
* @see [类、类#方法、类#成员]
*/
public void releaseSource(Statement statement, Connection conn, ResultSet resultSet)
{
if (null != resultSet)
{
try
{
resultSet.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (null != statement)
{
try
{
statement.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if (null != conn)
{
try
{
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
|