通过Java连接到MySQL时出现SQL语法错误

时间:2012-05-12 20:36:03

标签: java mysql syntax connection

我通过Java使用以下代码连接到数据库。

import java.sql.*;

public class Can {

//Database Credentials
private static String userName = "root";
private static String password = "root";
private static String databaseName = "books";

static Connection connection = null; // manages connection
static Statement statement = null; // query statement
static ResultSet resultSet = null; // manages results

static Can can;


public static void main(String[] args) {

    can = new Can();
    ResultSetMetaData metaData;
    int numberOfColumns;


    try {
        connection = DriverManager.getConnection("jdbc:mysql://localhost/"+databaseName, userName, password);
        statement = connection.createStatement();
        connection.setAutoCommit(false);

        //creating the tables
        statement.executeUpdate("CREATE TABLE Instructor" + "(instructorID INT, instructorName VARCHAR(30), PRIMARY KEY (instructorID))");
        statement.executeUpdate("CREATE TABLE Lecture" + "(lectureID INT, lectureName VARCHAR(30), time TIME, credit INT, instructorID INT, PRIMARY KEY (lectureID))");
        statement.executeUpdate("CREATE TABLE LectureStudent" + "(lectureID INT, studentID INT, PRIMARY KEY (lectureID, studentID))");
        statement.executeUpdate("CREATE TABLE Student" + "(studentID INT, studentName VARCHAR(30), CGPA FLOAT, PRIMARY KEY (studentID))");
        statement.executeUpdate("CREATE TABLE Assignment" + "(assignmentID INT, deadline INT(30), lectureID INT, PRIMARY KEY (assignmentID))");
        statement.executeUpdate("CREATE TABLE Results" + "(resultID INT, grade FLOAT, PRIMARY KEY (resultID)");


        //inserting info. into the tables
        statement.executeUpdate("INSERT INTO Instructor VALUES('1', 'instructorName1')");
        statement.executeUpdate("INSERT INTO Instructor VALUES('2', 'instructorName2')");

        statement.executeUpdate("INSERT INTO Lecture VALUES('1', 'lectureName1', '20:16:40', '3', '1')");
        statement.executeUpdate("INSERT INTO Lecture VALUES('2', 'lectureName2', '20:33:20', '4', '1')");
        statement.executeUpdate("INSERT INTO Lecture VALUES('3', 'lectureName3', '20:33:25', '4', '2')");

        statement.executeUpdate("INSERT INTO LectureStudent VALUES('1', '100')");
        statement.executeUpdate("INSERT INTO LectureStudent VALUES('2', '100')");
        statement.executeUpdate("INSERT INTO LectureStudent VALUES('3', '100')");

        statement.executeUpdate("INSERT INTO Student VALUES('100', 'studentName1', '2.4')");
        statement.executeUpdate("INSERT INTO Student VALUES('200', 'studentName2', '2.5')");
        statement.executeUpdate("INSERT INTO Student VALUES('300', 'studentName3', '2.6')");

        statement.executeUpdate("INSERT INTO Assignment VALUES('1000', '1969-12-31 10:40:00.0', '1')");

        statement.executeUpdate("INSERT INTO Results VALUES('1', '90.0')");


        //commit the transaction
        connection.commit();

        connection.setAutoCommit(true);


        resultSet = statement.executeQuery("SELECT assignmentID, deadline, lectureID FROM Assignment");
        metaData = resultSet.getMetaData();
        numberOfColumns = metaData.getColumnCount();
        System.out.println("assignment");
        can.displayTable(resultSet, numberOfColumns, metaData);


        resultSet = statement.executeQuery("SELECT instructorID, instructorName FROM Instructor");
        metaData = resultSet.getMetaData();
        numberOfColumns = metaData.getColumnCount();
        System.out.println("instructor");
        can.displayTable(resultSet, numberOfColumns, metaData);


        resultSet = statement.executeQuery("SELECT lectureID, lectureName, time, credit, instructorID FROM LectureStudent");
        metaData = resultSet.getMetaData();
        numberOfColumns = metaData.getColumnCount();
        System.out.println("lecture");
        can.displayTable(resultSet, numberOfColumns, metaData);


        resultSet = statement.executeQuery("SELECT lectureID, studentID FROM LectureStudent");
        metaData = resultSet.getMetaData();
        numberOfColumns = metaData.getColumnCount();
        System.out.println("lecture_student");
        can.displayTable(resultSet, numberOfColumns, metaData);


        resultSet = statement.executeQuery("SELECT resultID, grade FROM Result");
        metaData = resultSet.getMetaData();
        numberOfColumns = metaData.getColumnCount();
        System.out.println("result");
        can.displayTable(resultSet, numberOfColumns, metaData);


        resultSet = statement.executeQuery("SELECT studentID, studentName FROM Student");
        metaData = resultSet.getMetaData();
        numberOfColumns = metaData.getColumnCount();
        System.out.println("student");
        can.displayTable(resultSet, numberOfColumns, metaData);


    } catch (SQLException e) {
        e.printStackTrace();
    }
    finally {
        // close the connection!
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {}
    }

}//END main



public void displayTable(ResultSet resultSet, int numberOfColumns, ResultSetMetaData metaData) {

    try {
        for(int i=1; i<=numberOfColumns; i++)
            System.out.printf("%-8s\t", metaData.getColumnName(i));
        System.out.println();

        while( resultSet.next () ) {

            for( int i=1 ; i<=numberOfColumns ; i++)
                System.out.printf("%-8s\t", resultSet.getObject(i));
            System.out.println();

        }
    } catch (Exception e) { }



}//END displayTable

}//END Can

在创建表时,它工作正常。但问题是,当我运行程序时,我得到以下关于语法错误的奇怪错误。

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2677)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1748)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1665)
at Can.main(Can.java:35)

有什么想法吗?

谢谢,C @ N。

3 个答案:

答案 0 :(得分:5)

您在上一个Create语句中缺少右括号:... PRIMARY KEY (resultID)");

应该是:

    statement.executeUpdate("CREATE TABLE Results" + 
         "(resultID INT, grade FLOAT, PRIMARY KEY (resultID))");
                                                            ^
                                parenthesis added here -----|

答案 1 :(得分:1)

为什么要将''放在ID字段中......它是INT类型列。使您的插入查询像

statement.executeUpdate("INSERT INTO Instructor VALUES(1, 'instructorName1')");

您的上一个创建语句缺少右括号)

答案 2 :(得分:1)

如错误消息所示,请查看第35行?如果粘贴它们的行是正确的,那么这是最后一个创建Table语句?那里的SQL有问题。

更新:正如@ypercube对你的问题的评论所指出的那样:你错过了一个右括号!