1.定义预处理SQL语句;
2.为每一个“?”设置对应的值;
3.使用PreparedStatement操作数据库。
TestPreparedStmt.java:
- import java.sql.*;
- public class TestPreparedStmt {
- public static void main(String[] args) {
- Connection conn = null;
- PreparedStatement pstmt = null;
- String sql = null;
- int id = 0;
- String name = null;
- if (args.length != 2) {
- System.exit(-1);
- } else {
- id = Integer.parseInt(args[0]);
- name = args[1];
- }
- try {
- Class.forName("oracle.jdbc.driver.OracleDriver");
- conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:mgc", "system", "admin");
- sql = "Insert INTO member(id,name) VALUES(?,?)";
- pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, id);
- pstmt.setString(2, name);
- pstmt.executeUpdate();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- if (pstmt != null) {
- pstmt.close();
- pstmt = null;
- }
- if (conn != null) {
- conn.close();
- conn = null;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }