Step By Step(Java JDBC篇) (九)

2014-11-24 03:19:38 · 作者: · 浏览: 21
etConnection(

10 "jdbc:oracle:thin:@//192.168.1.101:1526/OraHome", conProps);

11 }

12

13 public static void main(String[] args) throws ClassNotFoundException {

14 Connection conn = null;

15 try {

16 conn = getConnection();

17 String strCreateTable = "create table product (name varchar2(20),birthyear int)";

18 conn.createStatement().execute(strCreateTable);

19 DatabaseMetaData dmd = conn.getMetaData();

20 //1. 确定该数据库服务器是否支持批量插入

21 if (dmd.supportsBatchUpdates()) {

22 //2. 将自动commit关闭,最后提交时刻的决定交由手工来完成

23 conn.setAutoCommit(false);

24 String sql = "INSERT into product VALUES( , )";

25 //3. 准备批量插入的数据

26 PreparedStatement prest = conn.prepareStatement(sql);

27 prest.setString(1, "A");

28 prest.setInt(2, 2002);

29 prest.addBatch();

30 prest.setString(1, "B");

31 prest.setInt(2, 1998);

32 prest.addBatch();

33 prest.setString(1, "C");

34 prest.setInt(2, 1980);

35 prest.addBatch();

36 prest.setString(1, "D");

37 prest.setInt(2, 1975);

38 prest.addBatch();

39 //4. 执行批量插入

40 int count[] = prest.executeBatch();

41 //5. 手动提交批量插入的数据到数据库服务器。

42 conn.commit();

43 }

44 } catch (Exception e) {

45 e.printStackTrace();

46 } finally {

47 try {

48 conn.close();

49 } catch (SQLException e) {

50 e.printStackTrace();

51 }

52 }

53 }

54 }

55 //通过Statement方式批量插入

56 public class MyTest {

57 private static Connection getConnection() throws SQLException,

58 ClassNotFoundException {

59 Class.forName("oracle.jdbc.driver.OracleDriver");

60 Properties conProps = new Properties();

61 conProps.put("user", "sys");

62 conProps.put("password", "helloworld");

63 conProps.put("internal_logon", "sysdba");

64 return DriverManager.getConnection(

65 "jdbc:oracle:thin:@//192.168.1.101:1526/OraHome", conProps);

66 }

67 public static void main(String[] args) throws ClassNotFoundException {

68 Connection conn = null;

69 try {

70 conn = getConnection();

71 String strCreateTable = "create table product1 (id int,name varchar2(20))";

72 conn.createStatement().execute(strCreateTable);

73 DatabaseMetaData dmd = conn.getMetaData();

74 if (dmd.supportsBatchUpdates()) {

75 conn.setAutoCommit(false);

76 Statement stmt = conn.createStatement();

77