動力節點筆記java
- import java.sql.*;
- import java.text.*;
- import java.util.*;
- //採用PreparedStatement添加數據
- public class InsertTest02 {
- public static void main(String[] args) {
- if (args.length != 8) {
- throw new IllegalArgumentException("參數非法,正確使用爲InsertTest01 ...");
- }
- Connection conn = null;
- PreparedStatement pstmt = null;
- try {
- //第一步,加載數據庫驅動,不一樣的數據庫驅動程序不同
- Class.forName("oracle.jdbc.driver.OracleDriver");
- //第二部,獲得數據庫鏈接
- String dburl = "jdbc:oracle:thin:@localhost:1521:orcl";
- //String dburl = "jdbc:oracle:thin:@192.168.21.1:1521:orcl";
- //String dburl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
- String userName = "system";
- String password = "wanwan";
- conn = DriverManager.getConnection(dburl, userName, password);
- //System.out.println(conn);
- int empno = Integer.parseInt(args[0]);
- String ename = args[1];
- String job = args[2];
- int mgr = Integer.parseInt(args[3]);
- //格式:yyyy-mm-dd
- String hiredate = args[4];
- float sal = Float.parseFloat(args[5]);
- float comm = Float.parseFloat(args[6]);
- int deptno = Integer.parseInt(args[7]);
- //第三步,建立Statement,執行SQL語句
- //採用佔位符的方式
- //最好將比較複雜的sql調通,再將sql語句和程序相結合,進行連調
- String sql = "insert into enp(empno, ename, job, mgr, hiredate, sal, comm, deptno) ";
- sql += "values(?, ?, ?, ?, ?, ?, ?, ?)";
- System.out.println("sql = " + sql);
- pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, empno);
- pstmt.setString(2, ename);
- pstmt.setString(3, job);
- pstmt.setInt(4, mgr);
- //日期轉換
- java.util.Date d = new SimpleDateFormat("yyyy-mm-dd").parse(hiredate);
- pstmt.setDate(5, new java.sql.Date(d.getTime()));
- pstmt.setFloat(6, sal);
- pstmt.setFloat(7, comm);
- pstmt.setInt(8, deptno);
- pstmt.executeUpdate();
- System.out.println("添加員工成功");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (ParseException e) {
- e.printStackTrace();
- } finally {
- //注意關閉原則:從裏到外
- try {
- if (pstmt != null) {
- pstmt.close();
- }
- if (conn != null) {
- conn.close();
- }
- } catch(SQLException e) {
- }
- }
- }
- }