2013-04-07 65 views
0

我试图在我的SQLite3数据库中的表中插入电子邮件ID。在我的情况下,它成功创建表,但在插入记录时出现错误 - “near”@gmail“:syntax error”。我该如何解决这个问题?这里是代码 -使用JDBC在SQLite数据库中插入电子邮件

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); 
     } 
    } 
} 

回答

2

你的核心错误是,对于插入查询,你没有用引号括住要插入的值。您的查询,施工后,看起来是这样的:

insert into T1 values([email protected], emailtexthere, 04-07-2013) 

当它应该是这样的:

insert into T1 values('[email protected]', 'emailtexthere', '04-07-2013') 

的SQL语法分析程序试图解析当前的查询,因为语法不正确扼流圈。此问题的解决方案是而不是只是简单地将引号括起来,而不是使用prepared statements。这是因为您现在构建查询的方式容易受到SQL injection attacks的影响。以下是使用预准备语句的示例:

PreparedStatement pStmt = conn.prepareStatement(
    "INSERT INTO T1 VALUES(?, ?, ?)"); 
pStmt.setString(1, emailId); 
pStmt.setString(2, gtse); 
pStmt.setDate(3, receivedDate); 
pStmt.execute(); 
+0

我当前的查询看起来像这样,因为我将变量插入数据库。插入到T1值(“emailId,gtse,receivedDate”)。 emailId,gtse和receivedDate是传递到此方法的变量 – Dan 2013-04-07 14:50:11

+2

使用预准备语句也会将值插入到数据库中,但它更安全,不太容易遇到您遇到的错误。 – Perception 2013-04-07 14:52:15

+0

非常感谢.. :) – Dan 2013-04-07 14:58:57