MySQL运行代码,但仅创建第一个表

时间:2019-03-30 18:51:38

标签: java jdbc

我正在开发一个应用程序,并使用JavaMysql连接到数据库。如标题所述,第二张表(autochans)没有创建。

我尝试在一条语句中运行两个SQL连接,但也失败了

这就是我使用java.sql。*连接到数据库的方式。

connection = DriverManager.getConnection("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database, this.user, this.password);

主要代码

public MySql initialize() {

    connect();

    try {
        connection.prepareStatement("SELECT 1 FROM guilds LIMIT 1").executeQuery();
    } catch (SQLException e) {
        try {
            connection.prepareStatement(
                    "CREATE TABLE IF NOT EXISTS `guilds` (\n" +
                            "  `id` text,\n" +
                            "  `prefix` text,\n" +
                            "  `joinmsg` text,\n" +
                            "  `leavemsg` text,\n" +
                            ") ENGINE=InnoDB DEFAULT CHARSET=utf8;"

            ).execute();

            connection.prepareStatement(
                    "CREATE TABLE IF NOT EXISTS `autochans` (\n" +
                            "  `chan` text,\n" +
                            "  `guild` text,\n" +
                            ") ENGINE=InnoDB DEFAULT CHARSET=utf8;"
            ).execute();

            System.out.println("MySql structure created...");
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }

    return this;
}

1 个答案:

答案 0 :(得分:0)

您需要删除最后一列的逗号。

尝试

        connection.prepareStatement(
                "CREATE TABLE IF NOT EXISTS `guilds` (\n" +
                        "  `id` text,\n" +
                        "  `prefix` text,\n" +
                        "  `joinmsg` text,\n" +
                        "  `leavemsg` text\n" +
                        ") ENGINE=InnoDB DEFAULT CHARSET=utf8"

        ).execute();

        connection.prepareStatement(
                "CREATE TABLE IF NOT EXISTS `autochans` (\n" +
                        "  `chan` text,\n" +
                        "  `guild` text\n" +
                        ") ENGINE=InnoDB DEFAULT CHARSET=utf8"
        ).execute();