字符串参数insert语句中的引号

时间:2013-07-05 04:14:09

标签: java sqlite insert

您好我一直在尝试通过java将字符串插入sqlite数据库。但是我在值sql语句中传递的字符串参数在其中有引号作为内容。我想这就是我为什么没有插入数据库的错误。有没有办法绕过insert语句中的引号。谢谢。

这是代码:

public void addNote(String topicadd, String contentadd) throws Exception
{   
    try
    {
        getConnection();
        statement = conn.createStatement();
        statement.executeUpdate("insert into tbl_notes (notes_topic, notes_content) values ('" + topicadd + "', '" + contentadd +"')");
        System.out.println("inserted note");
    }
    catch (Exception m)
    {`enter code here`
        System.out.println("error insert topic");
        System.out.println(m.getMessage());
    }
}

这是long的参数类型...这都在contentadd

import java.sql.*;

Resultset rset = null; (this has no new ResultSet() initialization)
Connection conn = null; (this has no new initialization too...)
Statement statement = null; (this has now new initialization)

always.....
try
{

}
catch (Exception e)   <- can switch e for any other alphabet
{
     e.getMessage();
    System.out.println("error this module"); <- personal practice
    throw e;
}

- getting connection

Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:m.db");
*** this is sqlite connection format 'm.db' is the database name

establish connection first..
statement syntax follows:
statement = conn.createStatement();
rset = statement.executeQuery("select * from tbl_notes");
- executeQuery is used for SELECT sql statements
rset = statement.executeUpdate("insert into tbl_notes (ID, status) values
('100', 'status here');

整个文本在字符串contentadd中,我正在制作一个简短的记笔记程序......好吧,它不执行插入语句...错误在命令提示符附近的某个地方(来自文本的单词)我正在使用sqlite ...如果您需要更多细节,请告诉我。再次感谢你。

1 个答案:

答案 0 :(得分:2)

使用PreparedStatement插入包含特殊字符的值:

getConnection();
PreparedStatement statement = conn.prepareStatement("insert into tbl_notes (notes_topic, notes_content) values (?, ?)");
statement.setString(1, topicadd);
statement.setString(2, contentadd);
statement.executeUpdate();

如您所见,您可以使用PreparedStatement的参数,该参数也可以包含引号。

此外,您还可以获得针对SQL注入的一些保护,因为PreparedStatement的字符串会相应地进行转义。