插入声明不会工作

时间:2011-04-03 11:59:32

标签: c# asp.net mysql sql html

嘿伙计我的代码没有错误,但是当我尝试下面的插入语句时似乎没有发生任何事情? 不知道我是如何包装文本框的,还是我的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);
    }
}

2 个答案:

答案 0 :(得分:4)

根据字段名称切换变量:

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

添加了新记录 ,但错误的用户因此在重新加载帖子时没有找到。

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

答案 1 :(得分:0)

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

变为

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

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

相关问题