2013-04-07 62 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