Posted on 2012-05-08 19:57
Xing 阅读(801)
评论(0) 编辑 收藏 所属分类:
基础
1 调用JDBC API executeBatch()方法。
2 不知道有没有直接调用sqlplus 的API。。
3 sqlplus username/pwd@oracle @1.sql
4
5 import java.sql.*;
6 import java.awt.*;
7 import java.util.List;
8 import java.util.ArrayList;
9 import java.io.*;
10 import java.lang.*;
11
12 public class Test {
13
14 /**
15 * @param args the command line arguments
16 */
17 public Test() {
18 try {
19 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
20 } catch (Exception e) {
21 System.out.println("加载驱动程序出错");
22 return;
23 }
24 }
25
26 List<String> loadSql(String sqlFile) throws Exception {
27 List<String> sqlList = new ArrayList<String>();
28 try {
29 InputStream sqlFileIn = new FileInputStream(sqlFile);
30 StringBuffer sqlSb = new StringBuffer();
31 byte[] buff = new byte[1024];
32 int byteRead = 0;
33 while ((byteRead = sqlFileIn.read(buff)) != -1) {
34 sqlSb.append(new String(buff, 0, byteRead));
35 } // Windows 下换行是 \r\n, Linux 下是 \n
36
37 String[] sqlArr = sqlSb.toString().split("(;\\s*\\r\\n)(;\\s*\\n)");
38 for (int i = 0; i < sqlArr.length; i++) {
39 String sql = sqlArr[i].replaceAll("--.*", "").trim();
40
41 if (!sql.equals("")) {
42 sqlList.add(sql);
43 }
44 }
45 return sqlList;
46 } catch (Exception ex) {
47 throw new Exception(ex.getMessage());
48 }
49 }
50 public static void main(String[] args) throws Exception {
51 String url = "jdbc:odbc:friends";
52 Connection con;
53 String sqlFile = "E:\\friends.sql";
54
55 try {
56 con = DriverManager.getConnection(url);
57 List<String> sqlList = new Test().loadSql(sqlFile);
58 Statement smt = con.createStatement();
59
60 for (String sql : sqlList) {
61 smt.addBatch(sql);
62 }
63 smt.executeBatch();
64
65 } catch (SQLException e) {
66 }
67
68 }
69 }
70
71 sql文件内不能有注释,friends.sql文件内容为
72 CREATE TABLE [dbo].[friends](
73 [name] [varchar](50) COLLATE NOT NULL,
74 [address] [varchar](50) COLLATE NULL,
75 [phone] [bigint] NULL,
76 [hireDate] [datetime] NULL,
77 [salary] [int] NULL
78 )
79