感謝大家對他們的幫助,閱讀他們的想法,我終於進口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);
編輯:添加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;
}
}
更改executeUpdate執行查詢,看它是否工作 – Satya
不,我只是測試「executeQuery」和「執行」,但他們都給了我完全相同的錯誤。 –
如果您使用'mysqldump'程序生成mySQL轉儲文件,加載它的最簡單方法是使用'mysqlimport'程序。 – DwB