我正在尝试使用INSERT命令将新用户添加到SQL数据库,但是当我运行它时会抛出一个错误,说它需要@Username参数。我给它这个参数:/
任何想法都出错了,iv尝试了大约两个小时来修复,但不知道什么是错的。
我正在使用ASP.Net网络表单和C#代码
下面的代码:
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.SqlClient;
using HashLibrary;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Data;
namespace LetsRentAgentZoneB
{
public partial class UserAdd : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LoginBtn_Click(object sender, EventArgs e)
{
ResultLbl.Text = Hasher.HashString(PasswordTxt.Text.Trim());
if (UsernameTxt.Text.Length <= 50 && PasswordTxt.Text.Length <= 25)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LetsRent"].ConnectionString);
SqlCommand cmd = new SqlCommand("AgentRegisterNewUser", conn);
//SqlParameter user = new SqlParameter();
//user.ParameterName = "@username";
//user.Value = UsernameTxt.Text.Trim();
//cmd.Parameters.Add(user);
cmd.Parameters.Add("@Username", SqlDbType.VarChar).Value = UsernameTxt.Text.Trim();
SqlParameter pass = new SqlParameter();
pass.ParameterName = "@password";
pass.Value = Hasher.HashString(PasswordTxt.Text.Trim());
cmd.Parameters.Add(pass);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
ResultLbl.Text = "User added!";
}
catch (Exception ex)
{
ResultLbl.Text = "error";
throw new Exception("Execption adding account. " + ex.Message);
}
}
catch (Exception ex)
{
ResultLbl.Text = "error";
throw new Exception("Execption adding account. " + ex.Message);
}
}
}
}
}
SQL命令
USE [LetsRent]
GO
/****** Object: StoredProcedure [dbo].[AgentRegisterNewUser] Script Date: 08/04/2014 14:03:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Chris
-- Create date: 08/04/2014
-- Description: Adds a new user to AgentUser Database
-- =============================================
ALTER PROCEDURE [dbo].[AgentRegisterNewUser]
-- Add the parameters for the stored procedure here
@Username VarChar(50),
@Password VarChar(25)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT @Username, @Password
INSERT INTO AgentUsers(Username, Password)
VALUES ( @Username, @Password);
END
答案 0 :(得分:2)
我猜AgentRegisterNewUser
是一个存储过程,因此cmd.CommandType应为StoredProcedure
:
SqlCommand cmd = new SqlCommand("AgentRegisterNewUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
如果您正在执行此更改,则执行包含文本“AgentRegisterNewUser”的T-SQL 批处理。这将编译以调用该过程,即使没有exec,但不会传递任何参数,因为你的参数传递给批。