【问题标题】:How to solve the Exception while storing the HashMap in MySQL database using java [duplicate]使用java将HashMap存储在MySQL数据库中时如何解决异常[重复]
【发布时间】:2019-09-03 06:21:40
【问题描述】:

我正在尝试将 HashMap 结果存储到 MySQL 数据库中。数据库包含两列对应HashMap的key和value。但是在将 HashMap 结果插入数据库表时出现了一些错误。以下是例外。

Exception in thread "main"
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 'Key, Value)
VALUES ('17/05/2018','11894060.45')' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) 
    at com.mysql.jdbc.Util.getInstance(Util.java:387)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478) 
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)   
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1541)
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2605)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1469)
    at com.ceino.Database.executeUpdate(Database.java:46)   
    at com.ceino.CSVwrite.writeCSVFile(CSVwrite.java:198)    
    at com.ceino.CSVwrite.main(CSVwrite.java:120)

数据库.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Database {
    private static String DRIVER_NAME = "com.mysql.jdbc.Driver";
    private static String URL = "jdbc:mysql://localhost:3306/Customer";
    private static String USERNAME = "root";
    private static String PASSWORD = "";
    private static Connection conn = null;

    public Database() {
        try {
            Class.forName(DRIVER_NAME);
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("Database Connection Initialized.");
    }

    public void closeConnection() {
        if (conn == null) return;
        try {
            conn.close();
            conn = null;
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public boolean execute(String sql) throws SQLException {
        if (conn
                == null)
            throw new SQLException("Connection null!");
        Statement statement = conn.createStatement();
        boolean res = statement.execute(sql);
        statement.close();
        return res;
    }

    public int executeUpdate(String sql) throws SQLException {
        if (conn
                == null)
            throw new SQLException("Connection null!");
        Statement statement = conn.createStatement();
        int res = statement.executeUpdate(sql);
        statement.close();
        return res;
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        if (conn == null)
            throw new SQLException("Connection null!");
        Statement statement = conn.createStatement();
        ResultSet res = statement.executeQuery(sql);
        statement.close();
        return res;
    }
}

FileWrite.java

static Database db = new Database();

    private static void writeCSVFile(HashMap<String, String> result) throws SQLException {

        for (Map.Entry<String, String> next : result.entrySet()) {

            String rslt1 = next.getKey();
            String rslt2 = next.getValue();
            db.executeUpdate("INSERT INTO amount (Key, Value) VALUES ('" + rslt1 + "','" + rslt2 + "');");
        }
        db.closeConnection();
    }

【问题讨论】:

  • 请格式化您的代码。我尽力格式化了。
  • 请您尝试删除 ;来自查询。
  • @KarthikeyanVaithilingam 谢谢。你能帮我解决问题吗?
  • @SujayMohan 我试过了。但同样的问题。

标签: java mysql exception jdbc hashmap


【解决方案1】:

Keyreserved keyword in MySQL,所以你必须转义它或用其他关键字更改它。

另外,永远不要在查询中使用串联字符串。而是使用PreparedStatement 来避免 SQL 注入攻击。

【讨论】:

  • 如果真的想使用关键字,请使用反引号,例如INSERT INTO amount (`Key`, `Value`) VALUES
  • @Karthikeyan Vaithilingam 这就是我的意思,对不起,我使用电话,我没有提到一个例子,谢谢你的有用评论:)
【解决方案2】:

首先,您不应该使用keyvalue 作为列名,因为它们属于MySQL 中的一组保留关键字。

现在您已经使用了它们,您需要在查询中使用 ` 对它们进行转义。

您的代码/查询应如下所示:

db.executeUpdate("INSERT INTO amount (`Key`, `Value`) VALUES ('" + rslt1 + "','" + rslt2 + "');");

这有望解决您的问题。

请注意,您应避免使用 + 号连接字符串,而应使用 String.format(),因为它有助于避免任何语法错误。

尽管在查询的情况下,您应该使用 PreparedStatement 而不是字符串连接,因为它可以帮助您避免 SQL 注入或任何其他类似的漏洞。

我希望这对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 2016-07-19
    • 1970-01-01
    • 2011-09-19
    • 2018-04-22
    • 2014-09-02
    • 2013-06-08
    相关资源
    最近更新 更多