2016-11-01 64 views
0

我想建立這個網站使用SQL參數。我以爲我遵循了我給出的例子,但是我的sql數據顯示'@username'和'number',而不是已經放入文本框的值。試圖讓sql參數工作

我很難過。

感謝您的幫助

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

那是因爲你把周圍的參數名稱報價在您的SQL INSERT語句。所以SQL認爲它是一個文字字符串,而不是對參數的引用。

試試這個:

runsql("INSERT INTO [dbo].[NumberOfVisitors] ([ResidentName],[NumberOfVisitors]) VALUES (@username,@number)", true); 
+0

哇。我不敢相信我做到了。我想我的問題是在代碼中,甚至沒有看我的字符串。謝謝 – birdseed

+0

只是爲了公平起見,上午6點,我一直在工作通宵 – birdseed

1

你必須忽略在SQL語句中的',因爲它不是一個字符串,而是一個參數:

runsql("INSERT INTO [dbo].[NumberOfVisitors] ([ResidentName],[NumberOfVisitors]) VALUES (@username,@number)", true); 
+0

哇。我不敢相信我做到了。我想我的問題是在代碼中,甚至沒有看我的字符串。謝謝 – birdseed

+0

只是爲了公平起見,早上6點,我一直在工作 – birdseed