MySQL JDBC语法错误

时间:2015-08-18 18:54:53

标签: mysql jdbc

我正在编写一个带有查询的简单数据库,该查询插入一些数据,修改一个条目,删除它,然后打印出其余的数据。

import java.sql.*;

public class SpotifyDB {
    //JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost/spotify";
    static final int portNumber = 3306;
    static final String serverName = "localhost";
    static final String dbName = "spotify";

    //Database credentials
    static final String USER = "root";
    static final String PASS = "root";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            //Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");

            //Open a connection to the database
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully...");

            //Insert data
        System.out.println("Inserting records into the table...");
        stmt = conn.createStatement();
        String sql = "INSERT INTO artist(artist) " +
                "values('Muse')";
        stmt.executeUpdate(sql);
        sql = "INSERT INTO album(album, artist, genre, year)" +
                "values('Drones', 'Muse', 'Rock', 2015)";
        stmt.executeUpdate(sql);
        sql = "INSERT INTO album(album, artist, genre, year)" +
                "values('The 2nd Law', 'Muse', 'Rock', 2012)";
        stmt.executeUpdate(sql);
        sql = ("INSERT INTO songs(song, artist, album, tracknumber, duration)" +
                "values('Madness', 'Muse', 'The 2nd Law', 2, '4:41')");
        stmt.executeUpdate(sql);
        sql = ("INSERT INTO songs(song, artist, album, tracknumber, duration)" +
                "values('Mercy', 'Muse', 'Drones', 4, '3:52')");
        stmt.executeUpdate(sql);
        System.out.println("Records inserted into the table!");

            //Update data
            String sql1 = "UPDATE songs " +
                    "SET track number = 1 WHERE song in ('Madness')";
            stmt.executeUpdate(sql1);

            //Delete data
            String sql2 = "DELETE FROM songs " +
                    "WHERE song = Madness";
            stmt.executeUpdate(sql2);

            //View records 
            String sql3 = "SELECT * FROM songs";
            ResultSet rs = stmt.executeQuery(sql3);

            while(rs.next()) {
                //Retrieve by column name
                String song  = rs.getString("song");
                String artist = rs.getString("artist");
                String album = rs.getString("album");
                String track = rs.getString("track number");
                String duration = rs.getString("duration");

                //Display the values
                System.out.print("Song: " + song);
                System.out.print(", Artist: " + artist);
                System.out.print(", Album: " + album);
                System.out.println(", Track: " + track);
                System.out.println(", Duration: " + duration);
            }

            //Close the connection, clean up running functions
            rs.close();
            stmt.close();
            conn.close();
        }
        catch(SQLException se) {
            //Handle errors for JDBC driver
            se.printStackTrace();
        }
        catch(Exception e) {
            //Handle errors for Class.forName
            e.printStackTrace();
        }
        finally {
            //finally used to close resources
            try{
                if(stmt!=null)
                    stmt.close();
            }
            catch(SQLException se2) {
            }
            try{
                if(conn!=null)
                    conn.close();
            }
            catch(SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

我的SQL数据库表也非常简单;

CREATE TABLE spotify.`songs` (
  `song` varchar(20) NOT NULL,
  `artist` varchar(20) NOT NULL,
  `album` varchar(20) NOT NULL,
  `track number` int(3) NOT NULL,
  `duration` varchar(10) NOT NULL,
  PRIMARY KEY (`song`),
  KEY `songalbum_idx` (`album`),
  KEY `songartist` (`artist`),
  CONSTRAINT `songalbum` FOREIGN KEY (`album`) REFERENCES `album` (`album`) 
  ON DELETE CASCADE 
  ON UPDATE CASCADE,
  CONSTRAINT `songartist` FOREIGN KEY (`artist`) REFERENCES `artist` (`artist`) 
  ON DELETE CASCADE 
  ON UPDATE CASCADE);

并且控制台正在返回此错误:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException 我无法看到表格列不匹配的位置,任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

列名确实不应该有空格,正是出于这个原因。但是,如果您的列名必须有空格,那么您需要使用与CREATE TABLE语句中完全相同的反向标记来限定它们:

INSERT INTO songs (song, artist, album, `track number`, duration) VALUES ...

否则在标识符track之后,查询引擎期望逗号(转到另一个标识符)或闭括号(结束列标识符列表)。它找不到这个,并立即找到另一个标识符(number,它甚至可能是一个保留字?)。这会混淆查询解析器。