原諒我是初學者,這個方法寫的很爛,以後不會改進,謝謝
/**
* 通過JDBC向數據庫中插入一條數據 1.Statement 用於執行SQL語句的對象 1.1 通過Connection 的
* createStatement() 方法來獲取 1.2 通過executeUpdate(sql) 的方法來執行SQL 1.3
* 傳入的SQL可以是INSERT/UPDATE/DELETE,但不能是SELECT
*
* 2.Connection和Statement使用後一定要記得關閉 需要在finally裡關閉其對象
* 2.1 關閉的順序:先關閉後獲取的
*/
@Test
public void testStatement() {
// 1.獲取數據庫連接
Connection connection = null;
// 4.執行插入
// 4.1 獲取操作SQL語句的Statement對象:
// 調用Connection的createStatement()方法來創建Statement的對象
Statement statement = null;
try {
connection = getConnection();
// 3.准備插入的SQL語句
String sql = "INSERT INTO customers (NAME,EMAIL,BIRTH) "
+"VALUES ('李小龍','long@live.com','1940-11-27')";
statement = connection.createStatement();
// 4.2 調用Statement對象的executeUpdate(sql) 執行SQL 語句的插入
statement.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 5.關閉Statement對象
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
// 2.關閉連接
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public Connection getConnection() throws Exception {
// 准備連接數據庫的四個字符串
// 驅動的全類名
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
String jdbcName = null;
// 讀取jdbcName.properties文件
InputStream inStream = getClass().getClassLoader().getResourceAsStream("properties/jdbcName.properties");
Properties propertiesOfName = new Properties();
propertiesOfName.load(inStream);
jdbcName = propertiesOfName.getProperty("jdbcName");
// 讀取需要的properties 文件
InputStream in = getClass().getClassLoader().getResourceAsStream("properties/" + jdbcName + ".properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
// 加載數據庫驅動程序(注冊驅動)
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
return connection;
}
數據庫配置如下
