簡體   English   中英

Java -> MySQL 查詢問題

[英]Java -> MySQL query issue

我正在嘗試創建一個 Java 查詢以插入到 MySQl,但我不斷收到錯誤消息。 請看下面的代碼。 PS與數據庫的連接很好。

這是正在調用的查詢

public  String newEmpInsert() {
    return newEmpInsert;
}

private String newEmpInsert = "INSERT INTO empInfo"
    + "(firstName, lastName, SSN, address, salary, pin, empLevel, contactInfo) "
    + "VALUES ("+firstName+", "+lastName+", "+SSN+", "+address+", "+salary+",  "+pin+","+empLevel+", "+contactInfo+")";

這是從主調用的處理程序

    public void newEmpInsert() {

    // SQL Connection
    Connection conn = null;
    try {
        conn = MySQL_connection_test.getConnection();
        // Create a statement
        Statement statement = conn.createStatement();
        statement.executeQuery(queries.newEmpInsert());

    } 
    catch (SQLException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
        System.out.println("--------->>Invalid query!!!!<<--------------");
        System.out.println("Your query has an error, please try again!!");
    }

    // Close the connection
    finally {
        try {
            conn.close();
            System.out.println("Database closed");
        } 
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Database closed");
    }
}

每次我運行查詢時,我都會收到無效的查詢捕獲。 變量在類和一切中被正確設置。

請將第三行更改為 VALUES 並嘗試用單引號將字符串值括起來。

private String newEmpInsert = "INSERT INTO empInfo"
+ "(firstName, lastName, SSN, address, salary, pin, empLevel, contactInfo) "
+ " VALUES ("+firstName+", "+lastName+", "+SSN+", "+address+", "+salary+", "+pin+", 
+ "+empLevel+", "+contactInfo+")";

您在這里的問題導致您構建了錯誤的 sql 語句。 當我查看您的代碼時,您在文本字段中缺少單引號。 此外,您的方法 build Statement 不好,使用特殊字符(如 ' 或 " )很容易失敗,並為 sql 注入附加公開。嘗試使用准備語句和綁定參數。

您需要從第三行末尾和第四行開頭的帶引號的字符串中刪除+

private String newEmpInsert = "INSERT INTO empInfo"
+ "(firstName, lastName, SSN, address, salary, pin, empLevel, contactInfo) "
+ "VALUE ("+firstName+", "+lastName+", "+SSN+", "+address+", "+salary+", "+pin+", "
    // added close quote at the end of the above line
+empLevel+", "+contactInfo+")";
    // plus sign and quote deleted at beginning of above line
private String newEmpInsert = "INSERT INTO empInfo"
    + "(firstName, lastName, SSN, address, salary, pin, empLevel, contactInfo) "
    + "VALUES ("+firstName+", "+lastName+", "+SSN+", "+address+", "+salary+",  
"+pin+","+empLevel+", "+contactInfo")";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM