我正在尝试构建此站点以使用sql params。我以为我已经按照我给出的示例,但我的sql数据显示'@ username'和'number',而不是放在文本框中的值。
我很难过。
感谢您的帮助
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;
public partial class management_Default : System.Web.UI.Page
{
public void runsql(string sqlCmdTxt, bool adduserbool)
{
SqlConnection sqlConnection = new SqlConnection("Server=DELLXPS\\SQLEXPRESS; Initial Catalog=Warren_SEINDATASYSTEMS; Integrated Security=true;");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = sqlCmdTxt;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection;
//If statement uses adduserbool param to determine if the code needs to make sql params for users
if (adduserbool == true)
{
SqlParameter user = new SqlParameter();
user.ParameterName = "@username";
user.Value = CreateUserWizard1.UserName.Trim();
cmd.Parameters.Add(user);
if (txtboxNumberOfVisitors.Text != "")
{
SqlParameter number = new SqlParameter();
number.ParameterName = "@number";
number.Value = txtboxNumberOfVisitors.Text;
cmd.Parameters.Add(number);
}
else
{
// this else will send "2" if the text box is empty
SqlParameter number = new SqlParameter();
number.ParameterName = "@number";
number.Value = "2";
cmd.Parameters.Add(number);
}
}
sqlConnection.Open();
//cmd.ExecuteScalar();
reader = cmd.ExecuteReader();
sqlConnection.Close();
//if user was created, clear number of visitors text box
if (adduserbool == true)
{
txtboxNumberOfVisitors.Text = "";
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
//Add residents to resident role
Roles.AddUserToRole(CreateUserWizard1.UserName, "resident");
runsql("INSERT INTO [dbo].[NumberOfVisitors] ([ResidentName],[NumberOfVisitors]) VALUES ('@username','@number')", true);
}
}
答案 0 :(得分:1)
你必须在sql语句中省略'
,因为它不是字符串,而是参数:
runsql("INSERT INTO [dbo].[NumberOfVisitors] ([ResidentName],[NumberOfVisitors]) VALUES (@username,@number)", true);
答案 1 :(得分:0)
那是因为你在SQL INSERT语句中的参数名称周围加了引号。所以SQL认为它是一个文字字符串,而不是对参数的引用。
试试这个:
runsql("INSERT INTO [dbo].[NumberOfVisitors] ([ResidentName],[NumberOfVisitors]) VALUES (@username,@number)", true);