【问题标题】:insert statement wont work插入语句不起作用
【发布时间】:2011-07-28 14:49:07
【问题描述】:

大家好,我的代码没有错误,但是当我尝试下面的插入语句时似乎什么也没发生?
不确定是我如何包装我的文本框还是我的 FriendID 查询字符串?

    protected void Button1_Click(object sender, EventArgs e)
    {
        string friendid = Request.QueryString["FriendID"];
        string theUserId = Session["UserID"].ToString();
        using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=***; User=***; Password=***;"))
        {
            cn.Open();
            using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + friendid + ", '" + TextBox1.Text + "', " + theUserId + ")", cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
        PopulateWallPosts(friendid);
    }
}

【问题讨论】:

  • 一方面,您需要修复这个主要 SQL 注入漏洞。 特别是,如果您的网站正在使用root 用户(它确实不应该使用)。就目前而言,您的数据库没有被修改这一事实是非常幸运的。
  • 也许可以尝试一下...catch 看看你是否到达 catch 块并检查 ex.message。
  • 调试时会发生什么? cmd.ExecuteNonQuery() 会被调用吗?当它执行时,命令的文本是什么? (由于您正在使用字符串连接,因此不妨暂时利用它来查看正在执行的完整 INSERT 语句。)

标签: c# asp.net mysql sql html


【解决方案1】:

您根据字段名称切换了变量:

using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + theUserId + ", '" + TextBox1.Text + "', " + friendid  + ")", cn))

新记录已添加,但用户输入错误,因此您稍后在重新加载帖子时没有找到它。

正如您已经知道的那样,通过使用参数而不是直接将值添加到 SQL 字符串来处理 SQL 注入风险。

【讨论】:

  • 嘿影子我切换它们是有原因的,我在朋友页面上工作,所以当您从自己的页面单击朋友时,根据我的查询字符串的 urlencode 切换它们以表示您的帖子在谁的墙上
  • @Garrith 可以,但要查看新插入的记录,则改为使用 PopulateWallPosts(friendid);。除非您正在使用一些数据库浏览器并且看不到任何内容被插入?
  • 是的,是按钮问题,现在一切正常!感谢您的时间影子
【解决方案2】:
"INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + friendid + ", '" + TextBox1.Text + "', " + theUserId + ")"

变成

"INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES ('" + friendid + "', '" + TextBox1.Text + "', '" + theUserId + "')"

必须使用单引号限定字符串。否则它们会被解析器视为变量。

【讨论】:

  • 如果值和字段是数字,则添加这些引号将导致类型不匹配错误。
  • 嗯,我认为它们是字符串...我的错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
  • 2019-02-14
相关资源
最近更新 更多