我正在尝试从JS运行在sql server中执行的查询。 此查询应根据用户名和密码在db中查找用户:
var str = "SELECT * FROM Users where (username = " + params.user + ") and (password = " + params.password + ")";
哪些参数是用户在url中发送的参数:
localhost:8888/login?user="abc"&password="123"
但str的价值是:
str = SELECT * FROM Users where (username = "abc") and (password = "123")
我尝试使用string.replace替换“with”,但是当我用“而不是”来打印它时写的str。
有什么建议吗?可能我不是第一个遇到这个问题的人......
答案 0 :(得分:0)
这样做:
var str = "SELECT * FROM Users where (username = " + params.user.replace(/"/g, "'") + ") and (password = " + params.password.replace(/"/g, "'") + ")";
它会用单引号替换双引号。
<强> See the DEMO here 强>
答案 1 :(得分:0)
以下是完成此任务的参数化SQL示例。
var str = "SELECT * FROM dbo.Users where (username = @username) and (password = @password)";
var command = new SqlCommand(str, connection);
var parameters = new List<SqlParameter>()
{
new SqlParameter("@username", SqlDbType.VarChar) { Size = 30, Value = params.user },
new SqlParameter("@password", SqlDbType.VarChar) { size = 30, Value = params.password },
};
command.Parameters.AddRange(parameters.ToArray());
答案 2 :(得分:-1)
在SELECT中插入',如下所示:
var str = "SELECT * FROM Users where (username = '" + params.user + "') and (password = '" + params.password + "')";
并删除“来自请求:
localhost:8888/login?user=abc&password=123