JdbcPreparedStatement(推荐使用)
package jdbc;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcPreparedStatementTest {
@Test
public void insertTest() throws Exception {
Connection connection = JdbcUtils.getConnection();
String sql = "insert into t_user(username,password,email) values(?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, "张三三");
ps.setString(2, "123456");
ps.setString(3, "zhangsan@qq.com");
ps.execute();
JdbcUtils.close(connection, ps);
}
@Test
public void deleteTest() throws SQLException {
Connection connection = JdbcUtils.getConnection();
String sql = "delete from t_user where username = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, "??");
ps.execute();
JdbcUtils.close(connection, ps);
}
@Test
public void updateTest() throws SQLException {
Connection connection = JdbcUtils.getConnection();
String sql = "update t_user set username = ? where username = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, "wangwu");
ps.setString(2, "liSi");
ps.execute();
JdbcUtils.close(connection, ps);
}
public void upDate(String sql, Object... args) {
Connection connection = null;
PreparedStatement ps = null;
try {
connection = JdbcUtils.getConnection();
ps = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i+1, args[i]);
}
ps.execute();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.close(connection, ps);
}
}
@Test
public void upDateTest() {
String sql = "insert into t_user(username,password,email) values(?,?,?)";
sql = "update t_user set username = ? where password = ?";
sql = "delete from t_user where username = ?";
upDate(sql, "xiaoQing");
}
}