调用JDBC API executeBatch()方法。
不知道有没有直接调用sqlplus 的API。。
sqlplus username/pwd@oracle @1.sql
import java.sql.*;
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.lang.*;
public class Test {
/**
* @param args the command line arguments
*/
public Test() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception e) {
System.out.println("加载驱动程序出错");
return;
}
}
ListloadSql(String sqlFile) throws Exception {
ListsqlList = new ArrayList();
try {
InputStream sqlFileIn = new FileInputStream(sqlFile);
StringBuffer sqlSb = new StringBuffer();
byte[] buff = new byte[1024];
int byteRead = 0;
while ((byteRead = sqlFileIn.read(buff)) != -1) {
sqlSb.append(new String(buff, 0, byteRead));
} // Windows 下换行是 \r\n, Linux 下是 \n
String[] sqlArr = sqlSb.toString().split("(;\\s*\\r\\n)(;\\s*\\n)");
for (int i = 0; i < sqlArr.length; i++) {
String sql = sqlArr[i].replaceAll("--.*", "").trim();
if (!sql.equals("")) {
sqlList.add(sql);
}
}
return sqlList;
} catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
public static void main(String[] args) throws Exception {
String url = "jdbc:odbc:friends";
Connection con;
String sqlFile = "E:\\friends.sql";
try {
con = DriverManager.getConnection(url);
ListsqlList = new Test().loadSql(sqlFile);
Statement smt = con.createStatement();
for (String sql : sqlList) {
smt.addBatch(sql);
}
smt.executeBatch();
} catch (SQLException e) {
}
}
}
sql文件内不能有注释,friends.sql文件内容为
CREATE TABLE [dbo].[friends](
[name] [varchar](50) COLLATE NOT NULL,
[address] [varchar](50) COLLATE NULL,
[phone] [bigint] NULL,
[hireDate] [datetime] NULL,
[salary] [int] NULL
)
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12593811/viewspace-720396/,如需转载,请注明出处,否则将追究法律责任。