我正在尝试将电子邮件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);
}
}
}
答案 0 :(得分:2)
您的核心错误是对于插入查询,您没有用引号括起要插入的值。在构建之后,您的查询看起来像这样:
insert into T1 values(whatever@gmail.com, emailtexthere, 04-07-2013)
什么时候应该是这样的:
insert into T1 values('whatever@gmail.com', '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();