データベース更新方法2(すごい様子)
3163 ワード
考え方:1.ツールクラスを用いて接続データベースをカプセル化し、接続リソースを解放する操作
2.一般的な更新方法で簡単で便利
jdbc.properties
driver=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/tan user=root password=1234
2.一般的な更新方法で簡単で便利
package tan.com;
import java.sql.Connection;
import java.sql.Statement;
import org.junit.Test;
public class TestJDBC {
/**
*
* : INSERT、UPDATE、DELETE
*
*/
public void update(String sql){
Connection conn = null;
Statement statement = null;
try {
conn = JDBCTools.getConnection();
statement = conn.createStatement();
statement.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.release(statement, conn);
}
}
@Test
public void testUpdate(){
String sql=null;
sql = "INSERT INTO user (name,age, school) " +"VALUES(' ', 22, ' ')";
this.update(sql);
System.out.println(" ~");
}
}
JDBCtools.javaツールメソッドpackage tan.com;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* JDBC . Version 1
*/
public class JDBCTools {
/**
* 1. . .
*
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
// 1. 4 .
// 1). Properties
Properties properties = new Properties();
// 2). jdbc.properties
InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
// 3). 2)
properties.load(in);
// 4). user, password 4 .
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String jdbcUrl = properties.getProperty("jdbcUrl");
String driver = properties.getProperty("driver");
// 2. ( Driver .)
Class.forName(driver);
// 3. DriverManager getConnection() .
return DriverManager.getConnection(jdbcUrl, user, password);
}
/**
* 2、
* Statement Connection ResultSet
* @param rs
* @param statement
* @param conn
*/
public static void release(ResultSet rs, Statement statement, Connection conn) {
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
/**
* Statement Connection
* @param statement
* @param conn
*/
public static void release(Statement statement, Connection conn) {
if (statement != null) {
try {
statement.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
jdbc.properties
driver=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/tan user=root password=1234