增加了一個Tools類,放了一些常用的工具
package com.JDBC.java;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* JDBC 的工具類
*/
public class JDBCTools {
/**
* 關閉Statement,Connection
*
* @param statement
* @param connection
*/
public static void release(Statement statement, Connection connection) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 獲取數據庫連接的方法
*
* @return
* @throws Exception
*/
public static Connection getConnection() {
// 准備連接數據庫的四個字符串
// 驅動的全類名
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
String jdbcName = null;
// 讀取jdbcName.properties文件
InputStream inStream = JDBCTools.class.getClassLoader().getResourceAsStream("properties/jdbcName.properties");
Properties propertiesOfName = new Properties();
try {
propertiesOfName.load(inStream);
} catch (IOException e) {
e.printStackTrace();
}
jdbcName = propertiesOfName.getProperty("jdbcName");
// 讀取需要的properties 文件
InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream("properties/" + jdbcName + ".properties");
Properties properties = new Properties();
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
// 加載數據庫驅動程序(注冊驅動)
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
try {
connection = DriverManager.getConnection(jdbcUrl, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
然後寫了一個比較通用的update方法
/**
* 通用的更新方法:包括INSERT/UPDATE/DELETE
* @param sql
*/
public void update(String sql){
Connection connection = null;
Statement statement = null;
try {
connection = JDBCTools.getConnection();
statement = connection.createStatement();
statement.executeUpdate(sql);
}catch (Exception e) {
e.printStackTrace();
}finally{
JDBCTools.release(statement, connection);
}
}
懶得寫測試類,肯定好使,相信我~