用Java鏈接數據庫並執行數據庫文件。實現初始化數據庫(判斷數據庫插入數據時是否有表,有就插入,沒有就創建。)
報錯信息:
begin
執行了:0
更新錯誤
java.sql.BatchUpdateException: “;”附近有語法錯誤。
at sqljdbc4/com.microsoft.sqlserver.jdbc.SQLServerStatement.executeBatch(SQLServerStatement.java:1723)
at com.qfx.test.TestReadFile.getData(TestReadFile.java:47)
at com.qfx.test.TestReadFile.main(TestReadFile.java:15)
0
源代碼如下:
package com.qfx.test;
import java.io.*;
import java.sql.*;
/**
* 讀取指定文件下sql腳本,執行到數據庫
* 朱行讀取分批處理批量插入數據庫
*/
public class TestReadFile {
public static void main(String[] args) {
System.err.println("begin");
long start = System.currentTimeMillis();
String path = "D:\\chushihua.sql";
getData(path);
System.err.print((System.currentTimeMillis() - start) / 1000);
}
private static void getData(String path) {
//讀取文件
BufferedReader reader;
Connection conn = null;
Statement pst = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;DatabaseName=StudentTest", "sa", "123456");
pst = conn.createStatement();
reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
pst.addBatch(line);
/* System.out.println("-----------------------");
System.out.println(line);
System.out.println("-----------------------");*/
if (i % 100 == 0) {
System.out.println("執行了:" + i);
pst.executeBatch();
}
i += 1;
}
reader.close();
// 執行批量更新
pst.executeBatch();
}
catch (Exception e) {
//此處判斷是否在批量更新處拋出異常
System.out.println("更新錯誤");
e.printStackTrace();
} finally {
try {
if (pst != null) {
pst.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
求助一下,一直找不到問題。