【问题标题】:quotation marks in string parameter insert statement字符串参数插入语句中的引号
【发布时间】:2013-07-05 04:14:09
【问题描述】:

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

这是代码:

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

这是一个很长的参数...这都在 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 ...如果您需要更多详细信息,请告诉我。再次感谢。

【问题讨论】:

  • 你能发布一些代码吗?
  • 对不起,我现在发布了涉及的代码。谢谢。
  • @DanD。请注意,参数化查询在 Java 中称为 PreparedStatement

标签: java sqlite insert


【解决方案1】:

使用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 的字符串会相应地进行转义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    相关资源
    最近更新 更多