如何从Java应用程序将SQL文件(存储在Java项目的源文件夹中)加载到MySQL中? [英] How to load a SQL file (stored in the source folder of my Java project) into MySQL from a Java Application?
问题描述
我想在运行时从我的Java应用程序将一个SQL文件(存储在NetBeans Java项目的源文件夹中)加载到MySQL中.我该怎么办?
I want to load an SQL file (which is stored in the source folder of my NetBeans Java Project) into MySQL from my Java Application during runtime. How can I do this?
SQL文件的大小为15.15 MB,我想知道是否可以复制到字符串中吗?或者,如果我设法将其复制到字符串(尽管它可能会抛出内存不足错误),那么如何一次性执行多个命令(因为SQL文件包含许多命令).
The SQL file is 15.15 MB in size and I am wondering whether I can copy into a String or not? Or if I anyhow manage to copy it to a String (though it may throw out of memory error), how to execute multiple commands in one go (because the SQL file contains many commands).
我想在不使用任何其他工具的情况下做到这一点.只需使用Java中预先存在的库和类(与JDK捆绑在一起)即可.
I want to do it without using any additional tools. Just using pre-existing libraries and classes in java (that are bundled with JDK).
推荐答案
我发现,如果不添加其他工具和库,可能无法做到这一点.
我们可以通过将SQL文件拆分为较小的SQL文件(每个文件仅包含一个SQL命令),然后启动一个循环以一次执行所有这些文件的方式来做到这一点.我试过了,它可以工作.当然可以.
We can do it by splitting the SQL file into smaller SQL files, each containing just one SQL command and then initiating a loop to execute all those files at once. I'd tried it and it works. It certainly does.
以下是我用来执行此操作的代码:
The following is the code I used to do that :
import javax.swing.* ;
import java.sql.* ;
import java.io.* ;
public class LoadSQLFile {
public static void main(string args[ ]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
String password = JOptionPane.showInputDialog(null, "We need your MySQL Password to run the application. Please enter it here.", " MySQL Password ?", JOptionPane.QUESTION_MESSAGE) ;
Class.forName("java.sql.Driver") ;
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/MyDB", "root", password) ;
Statement stmt = conn.createStatement() ;
int i = 0 ;
for(i=1;i<=16;i++) {
FileReader fr = new FileReader("src//sql_files//BCK"+i+".sql") ;
BufferedReader br = new BufferedReader(fr) ;
stmt.execute(br.readLine()) ;
}
stmt.close();
conn.close();
JOptionPane.showMessageDialog(null, " Records Successfully Inserted into database !", "Success !", 1) ;
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e, "ERROR", JOptionPane.ERROR_MESSAGE) ;
}
}
});
}
}
我要执行存储在项目的源文件夹中的SQL文件,该文件名为"sql_files".文件的名称为-BCK1.sql,BCK2.sql,....,BCK16.sql.每个文件仅在第一行中包含一个SQL文件.对我来说效果很好.
I was to execute SQL files stored in my project's source folder inside a package named "sql_files". The names of the files are - BCK1.sql, BCK2.sql, ...., BCK16.sql. Each file contained just one SQL file in just first line. It worked just fine for me.
我为此使用了MySQL JDBC驱动程序.
这篇关于如何从Java应用程序将SQL文件(存储在Java项目的源文件夹中)加载到MySQL中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!