如何在 ADO.NET 查询中放置双引号? [英] How to put double quotes in ADO.NET query?

查看:45
本文介绍了如何在 ADO.NET 查询中放置双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的所有查询中防止任何 SQL 注入,并想知道如何在此查询中放置双引号.谢谢

I am trying to prevent any SQL injection in all my queries and would like to know how to put double quotes in this query. Thanks

string.Format("SELECT TOP 10 article_guid, article_title 
               FROM article 
               WHERE article.article_isdeleted = 0 AND 
                     FREETEXT(article_title, @val)");

推荐答案

第 1 步:不要这样做.改用参数化查询.

Step 1: Don't do this. Use a parameterized query instead.

参数化查询消除了与 SQL 注入攻击相关的大部分风险.

Parameterized queries remove most of the risk associated with SQL injection attacks.

来自链接:

private void CallPreparedCmd() {
    string sConnString = 
        "Server=(local);Database=Northwind;Integrated Security=True;";
    string sSQL = 
        "UPDATE Customers SET City=@sCity WHERE CustomerID=@sCustomerID";
    using (SqlConnection oCn = new SqlConnection(sConnString)) {
        using (SqlCommand oCmd = new SqlCommand(sSQL, oCn)) {
            oCmd.CommandType = CommandType.Text;

            oCmd.Parameters.Add("@sCustomerID", SqlDbType.NChar, 5);
            oCmd.Parameters.Add("@sCity", SqlDbType.NVarChar, 15);

            oCn.Open();
            oCmd.Prepare();

            oCmd.Parameters["@sCustomerID"].Value = "ALFKI";
            oCmd.Parameters["@sCity"].Value = "Berlin2";
            oCmd.ExecuteNonQuery();

            oCmd.Parameters["@sCustomerID"].Value = "CHOPS";
            oCmd.Parameters["@sCity"].Value = "Bern2";
            oCmd.ExecuteNonQuery();

            oCn.Close();
        }
    }
}

话虽如此,您可以通过像这样转义双引号将引号插入到字符串中:

That being said, you can insert quotes into a string by escaping the double quotes like this:

string newstring = " \"I'm Quoted\" ";

这篇关于如何在 ADO.NET 查询中放置双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆