将转储文件导入 mysql JDBC

Mak*_*ebi 1 java mysql jdbc mysqlimport

我正在使用 Java 和 MySQL (JDBC),并且我想将转储文件导入到数据库。这样做的正确方法是什么?我尝试过以下代码:

// function "connectToDB" connects to the Database, and not the server.
// variable sourcePath refers to the dumpfile.
    Connection con = connectToDB(USERNAME, PASSWORD); 
    String q = "source " + sourcePath;
    System.out.println("Q is: " + q);
    try {
        Statement statement = con.createStatement();
        statement.executeUpdate(q);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    closeConnection(con);
Run Code Online (Sandbox Code Playgroud)

但我得到一个 MySQLSyntaxErrorException :

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行“source C:...\Desktop\dumpfile.sql”附近​​使用的正确语法

Mak*_*ebi 5

感谢大家的帮助,阅读他们的想法,我终于导入了 dumpfile.sql 所以如果有人遇到同样的问题,对我有用的示例代码是这样的:

Connection con = connectToDB(USERNAME, PASSWORD);
/* Note that con is a connection to database, and not the server.
if You have a connection to the server, the first command in the dumpfile should be the
USE db_name; */
String q = "";
File f = new File(sourcePath); // source path is the absolute path of dumpfile.
try {
    BufferedReader bf = new BufferedReader(new FileReader(f));
        String line = null;
        line = bf.readLine();
        while (line != null) {
            q = q + line + "\n";
            line = bf.readLine();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
// Now we have the content of the dumpfile in 'q'.
// We must separate the queries, so they can be executed. And Java Simply does this:
String[] commands = q.split(";");

try {
    Statement statement = con.createStatement();
    for (String s : commands) {
        statement.execute(s);
    }
} catch (Exception ex) {
}
closeConnection(con);
Run Code Online (Sandbox Code Playgroud)

编辑:添加 connectToDB 函数:

private Connection connectToDB(String username, String password) {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/" + DATABASE;
        Properties objProperties = new Properties();
        objProperties.put("user", username);
        objProperties.put("password", password);
        objProperties.put("useUnicode", "true");
        objProperties.put("characterEncoding", "utf-8");

        Connection con = DriverManager.getConnection(url, objProperties);
        return con;
    } catch (Exception ex) {
        System.out.println("Connection to sql database failed.");
        ex.printStackTrace();
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)