0

我正在尝试将电子邮件 ID 插入到我的 SQLite3 数据库中的表中。在我的情况下,它成功创建了表,但在其中插入记录时出错 - “靠近“@gmail”:语法错误”。我该如何解决这个问题?这是代码 -

public void insertData(String emailId, double gtse, long receivedDate) throws ClassNotFoundException, SQLException{
    Class.forName("org.sqlite.JDBC");
    Connection connection = null;

    try
    {
      // create a database connection
      connection = DriverManager.getConnection("jdbc:sqlite:testdb.sqlite");
      Statement statement = connection.createStatement();
      statement.setQueryTimeout(30);  // set timeout to 30 sec.

      ResultSet result = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='T1'");
      if(!result.next()){
          statement.executeUpdate("create table T1 (email TEXT, gtse REAL, receiveddate DATE)");

      statement.executeUpdate("insert into T1 values(" + emailId + ", "+ gtse +", "+ receivedDate +")");      
      }
      else{

      }

    }
    catch(SQLException e)
    {
      // if the error message is "out of memory", 
      // it probably means no database file is found
      System.err.println(e.getMessage());
    }
    finally
    {
      try
      {
        if(connection != null)
          connection.close();
      }
      catch(SQLException e)
      {
        // connection close failed.
        System.err.println(e);
      }
    }
}
4

1 回答 1

3

您的核心错误是,对于插入查询,您没有将要插入的值括在引号中。您的查询在构建后看起来像这样:

insert into T1 values(whatever@gmail.com, emailtexthere,  04-07-2013)

什么时候应该是这样的:

insert into T1 values('whatever@gmail.com', 'emailtexthere',  '04-07-2013')

SQL 解析器在尝试解析当前查询时阻塞,因为语法不正确。这个问题的解决方案不是简单地将值括在引号中,而是使用准备好的语句。这是因为您现在构建查询的方式很容易受到SQL 注入攻击。以下是使用准备好的语句的示例:

PreparedStatement pStmt = conn.prepareStatement(
    "INSERT INTO T1 VALUES(?, ?, ?)");
pStmt.setString(1, emailId);
pStmt.setString(2, gtse);
pStmt.setDate(3, receivedDate);
pStmt.execute();
于 2013-04-07T14:35:16.537 回答