Eclipse中的MySql语法错误(java)

时间:2017-03-29 23:53:31

标签: java mysql eclipse

我正在使用Eclipse和Xampp。我编写了这段代码,它应该连接到服务器,创建数据库,表并用一些名称填充它:

import java.sql.*;

public class Database {

    public static void main(String[] args) 
    {
        String user = "root" , pass = "" , url = 
"jdbc:mysql://127.0.0.1:3306/";
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conn = DriverManager.getConnection(url, user, pass);
            Statement stat = conn.createStatement();

            stat.execute("CREATE DATABASE IF NOT EXISTS Database");
            stat.execute("USE Database");

            stat.execute("DROP TABLE IF EXISTS Names");
            stat.execute("CREATE TABLE Names ("+
                    "id BIGINT NOT NULL AUTO_INCREMENT,"
                    + "fname VARCHAR(25),"
                    + "lname VARCHAR(25),"
                    + "PRIMARY KEY(id)"
                    + ")");

            stat.execute("INSERT INTO Names (fname , lname) VALUES"+"('Jan', 
'Kowalski'), (Ala', 'Kowalski'), ('James', 'Bobo')");

            ResultSet res = stat.executeQuery("SELECT * FROM Names WHERE 
lname = 'Kowalski'");
            while (res.next())
            {
                System.out.println(res.getString("fname") + " " + 
res.getString("lname"));
            }
            System.out.println("");


        }
        catch(Exception e)
        {
            e.printStackTrace();
        }


    }

}

我收到以下错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error 
in your SQL syntax; check the manual that corresponds to your MariaDB server 
version for the right syntax to use near 'Database' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2497)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2455)
at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:839)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:739)
at Database.main(Database.java:14)

我已经尝试查阅一些文档,看看是否有遗漏但却无法找到的内容。

1 个答案:

答案 0 :(得分:0)

除了Database之外,您需要为该数据库提供一个名称,因为这是MySQL中的保留字。替换这两行:

stat.execute("CREATE DATABASE IF NOT EXISTS MyDatabase");
stat.execute("USE MyDatabase");

MyDatabase替换为您想要命名的内容。