插入语句不起作用
本文关键字:不起作用 语句 插入 | 更新日期: 2023-09-27 17:48:54
嘿伙计们,我的代码没有收到任何错误,但是当我尝试下面的插入语句时似乎什么也没发生?
不确定是我包装文本框的方式还是我的 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);
}
}
您根据字段名称切换了变量,它应该是:
using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + theUserId + ", '" + TextBox1.Text + "', " + friendid + ")", cn))
添加了新记录,但针对的是错误的用户,因此您稍后在重新加载帖子时没有找到它。
正如您已经被告知的那样,通过使用参数而不是直接将值添加到SQL字符串来处理SQL注入风险。
"INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + friendid + ", '" + TextBox1.Text + "', " + theUserId + ")"
成为
"INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES ('" + friendid + "', '" + TextBox1.Text + "', '" + theUserId + "')"
必须使用单引号限定字符串。 否则,解析器将它们视为变量。