JDBC PreparedStatement共通の添削操作を実現
20282 ワード
1、PreparedStatementは共通の添削操作を実現する
package com.atguigu2.preparedstatement.crud;
/* preparedstatement Statement,
*
* ;
*
*/
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import org.junit.Test;
import com.atguigu3.util.JDBCUtils;
public class PreparedStatementTest {
@Test
public void testCommonUpdate() {
// String sql="delete from customers where id = ?";
// update(sql,3);
String sql="update `order` set order_name=? where order_id=?";
update(sql, "DD","2");
}
// ( )
public void update(String sql,Object ...args) {//sql
Connection conn=null;
PreparedStatement ps=null;
try {
//1、
conn = JDBCUtils.getConnectio();
//2、 sql , PrepareStatement
ps = conn.prepareStatement(sql);
//3、
for(int i=0;i<args.length;i++) {
ps.setObject(i+1,args[i]);//
}
//4、
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}finally {
//5、
JDBCUtils.closeResource(conn, ps);
}
}
//---------------------------------------------------------------
// customers
@Test
public void testUpdate() {
Connection conn=null;
PreparedStatement ps=null;
try {
//1、
conn = JDBCUtils.getConnectio();
//2、 sql , PrepareStatement
String sql="update customers set name= ? where id= ?";//?:
ps = conn.prepareStatement(sql);
//3、
ps.setObject(1," ");
ps.setObject(2,18);
//4、
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}finally {
//5、
JDBCUtils.closeResource(conn, ps);
}
}
// customer
@Test
public void testInsert() {
//3
Connection conn=null;
PreparedStatement ps=null;
try {
//1 4
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user=pros.getProperty("user");
String password=pros.getProperty("password");
String url=pros.getProperty("url");
String driverClass=pros.getProperty("driverClass");
//2
Class.forName(driverClass);
conn = DriverManager.getConnection(url, user, password);
// System.out.println(conn);
//4、 SQL , prepareStatement
String sql="insert into customers(name,email,birth)values(?,?,?)";//?:
ps = conn.prepareStatement(sql);
//5、
ps.setString(1, " ");
ps.setString(2,"[email protected]");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = sdf.parse("1000-01-01");
ps.setDate(3,new Date(date.getTime()));
//6、 SQL
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}finally {
//7、
try {
if (ps!=null)
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}