使用带有 JDBC 的 MySQL 运行 .sql 脚本

新手上路,请多包涵

我开始将 MySQL 与 JDBC 一起使用。

 Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///x", "x", "x");
stmt = conn.createStatement();
stmt.execute( "CREATE TABLE amigos" +
            "("+
            "id          int AUTO_INCREMENT          not null,"+
            "nombre      char(20)                    not null,"+
            "primary key(id)" +
            ")");

我要创建 3-4 个表,这看起来不太好。

有没有办法从 MySQL JDBC 运行 .sql 脚本?

原文由 Macarse 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 808
2 个回答

好的。你可以在你的项目中使用这个类(由于文件长度而发布在 pastebin 上)。但请记住保留 apache 许可证信息。

JDBC ScriptRunner

它是删除了依赖项的 iBatis ScriptRunner 的盗版。

你可以像这样使用它

Connection con = ....
ScriptRunner runner = new ScriptRunner(con, [booleanAutoCommit], [booleanStopOnerror]);
runner.runScript(new BufferedReader(new FileReader("test.sql")));

而已!

原文由 jitter 发布,翻译遵循 CC BY-SA 3.0 许可协议

你能用这个吗:

 public static void executeSQL(File f, Connection c) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(f));
    String sql = "", line;
    while ((line = br.readLine()) != null) sql += (line+"\n");
    c.prepareCall(sql).execute(sql);
}

此函数获取 SQL 文件和 DB 连接。然后它使用 java.io 中的 BufferedReader 逐行读取文件。

最后,执行读取语句。

Java 8+ 版本:

 public static void executeSQL(Path p, Connection c) throws Exception {
    List<String> lines = Files.readAllLines(p);
    String s = String.join("\n", lines.toArray(new String[0]));
    c.prepareCall(s).execute(s);
}

原文由 Muskovets 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题