I have a stored procedure that returns a variable #result set to 1 or 0 (datatype bit). I am accessing it in my C# with the following code. Its throwing an error saying too many parameters.
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
SqlCommand Cmd = new SqlCommand("usp_CheckEmailMobile", con);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.CommandText = "Registration";
Cmd.Parameters.AddWithValue("#Name", txtName.Text);
Cmd.Parameters.AddWithValue("#Email", txtEmailAddress.Text);
Cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
Cmd.Parameters.AddWithValue("#CountryCode", ddlCountryCode.Text);
Cmd.Parameters.AddWithValue("#Mobile", txtMobileNumber.Text);
//Cmd.Parameters.Add("#Result", DbType.Boolean);
SqlParameter sqlParam = new SqlParameter("#Result", DbType.Boolean);
//sqlParam.ParameterName = "#Result";
//sqlParam.DbType = DbType.Boolean;
sqlParam.Direction = ParameterDirection.Output;
Cmd.Parameters.Add(sqlParam);
Cmd.ExecuteNonQuery();
con.Close();
Response.Write(Cmd.Parameters["#Result"].Value);
}
the stored procedure: (this I think is fine...) And please correct my CS code...
ALTER PROCEDURE [dbo].[usp_CheckEmailMobile](
#Name VARCHAR(50),
#Email NVARCHAR(50),
#Password NVARCHAR(50),
#CountryCode INT,
#Mobile VARCHAR(50),
#Result BIT OUTPUT)
AS
BEGIN
IF EXISTS (SELECT COUNT (*) FROM AUser WHERE [Email] = #Email AND [Mobile] = #Mobile)
Begin
Set #Result=0; --Email &/or Mobile does not exist in database
End
ELSE
Begin
--Insert the record & register the user
INSERT INTO [AUser] ([Name], [Email], [Password], [CountryCode], [Mobile]) VALUES (#Name, #Email, #Password, #CountryCode, #Mobile)
Set #Result=1;
End
END
you can try this code :
bool result=false;
SqlCommand scCommand = new SqlCommand("usp_CheckEmailMobile", sqlCon);
scCommand.CommandType = CommandType.StoredProcedure;
scCommand.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = txtName.Text;
scCommand.Parameters.Add("#Email", SqlDbType.NVarChar, 50).Value = txtEmailAddress.Text;
scCommand.Parameters.Add("#Password ", SqlDbType.NVarChar, 50).Value = txtPassword.Text;
scCommand.Parameters.Add("#CountryCode", SqlDbType.VarChar.50).Value =ddlCountryCode.SelectedText;
scCommand.Parameters.Add("#Mobile", SqlDbType.NVarChar, 50).Value = txtMobileNumber.Text;
scCommand.Parameters.Add("#Result ", SqlDbType.Bit).Direction = ParameterDirection.Output;
try
{
if (scCommand.Connection.State == ConnectionState.Closed)
{
scCommand.Connection.Open();
}
scCommand.ExecuteNonQuery();
result = Convert.ToBoolean(scCommand.Parameters["#Result"].Value);
}
catch (Exception)
{
}
finally
{
scCommand.Connection.Close();
Response.Write(result);
}
Why do you set:
Cmd.CommandText = "Registration";
this will replace your stored procedure name, so it won't call the stored procedure you indicated in:
SqlCommand Cmd = new SqlCommand("usp_CheckEmailMobile", con);
It can be useful to use a SQL profiler to debug that the SQL going "over the wire" is as expected.
Related
When using this code, I get an error
Procedure or function 'Registration' expects parameter '#qUsername', which was not supplied
Can someone please tell me how to fix this? This is my controller code and the SQL query for registration
public ActionResult Create([Bind(Include = "UserID,Username,FirstName,LastName,Email,Password,Number,IsAdmin,Salt")] UsersTable usersTable)
{
if (ModelState.IsValid)
{
Int32 rowsAffected;
SqlCommand cmd = new SqlCommand();
SqlConnection sqlConnection1 = new SqlConnection(#"xxx");
cmd.CommandText = "dbo.Registration";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();
return RedirectToAction("Index");
}
return View(usersTable);
}
Procedure code:
CREATE PROCEDURE dbo.Registration
#qUsername NVARCHAR(50),
#qPassword NVARCHAR(50),
#qFirstName NVARCHAR(40),
#qLastName NVARCHAR(40),
#errorResponse NVARCHAR(250) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #salt UNIQUEIDENTIFIER = NEWID()
BEGIN TRY
INSERT INTO dbo.UsersTable (UserID, Password, Salt, FirstName, LastName)
VALUES (#qUsername, HASHBYTES('SHA2_512', #qPassword + CAST(#salt AS NVARCHAR(36))), #salt, #qFirstName, #qLastName)
SET #errorResponse = 'Success'
END TRY
BEGIN CATCH
SET #errorResponse = ERROR_MESSAGE()
END CATCH
END
You need to define and set the parameters for the stored procedure before your call it from your C# code - like this:
cmd.CommandText = "dbo.Registration";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
// define and set parameters!
cmd.Parameters.Add("#qUsername", SqlDbType.NVarChar, 50).Value = .....;
cmd.Parameters.Add("#qPassword", SqlDbType.NVarChar, 50).Value = .....;
cmd.Parameters.Add("#qFirstName", SqlDbType.NVarChar, 40).Value = .....;
cmd.Parameters.Add("#qLastName", SqlDbType.NVarChar, 40).Value = .....;
cmd.Parameters.Add("#errorResponse", SqlDbType.NVarChar, 250).Direction = ParameterDirection.Output;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();
Use the following:
cmd.Parameters.AddWithValue("#qUsername", "xxxxx");
For all parameters before calling:
cmd.ExecuteNonQuery();
I'm creating a page that inserts user information into a SQL server. I want to check to make sure that the database table doesn't already have the user EDIPI number in it and if it does not than it insert the new provided information. My error message is:
Procedure or function 'TestTableInsert' expects parameter '#EDIPI', which was not supplied.
My btnSaveSP_Click should allow the user to insert the information in to the database but I believe my Stored Procedure is wrong.
My Button Code:
protected void btnSaveSP_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand();
SqlCommand sqlCmd = new SqlCommand("TestTableInsert", sqlconn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlcomm.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 50).Value = txtEDIPI.Text;
sqlcomm.Parameters.Add("#First", SqlDbType.NVarChar, 50).Value = txtFirstName.Text;
sqlCmd.ExecuteNonQuery();
sqlconn.Close();
}
My Stored Procedure code:
ALTER PROCEDURE [dbo].[TestTableInsert]
#EDIPI nvarchar(50),
#First nvarchar(50)
AS
BEGIN
IF NOT EXISTS (SELECT * FROM TestTable where EDIPI = #EDIPI)
BEGIN
INSERT INTO TestTable (EDIPI,First)
VALUES (#EDIPI, #First)
END
END
You need to change
sqlcomm.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 50).Value = txtEDIPI.Text;
sqlcomm.Parameters.Add("#First", SqlDbType.NVarChar, 50).Value = txtFirstName.Text;
into
sqlCmd.Parameters.Add("#EDIPI", SqlDbType.NVarChar, 50).Value = txtEDIPI.Text;
sqlCmd.Parameters.Add("#First", SqlDbType.NVarChar, 50).Value = txtFirstName.Text;
Note that in the first you use sqlcomm while it should be sqlCmd
private void btnInsert_Click(object sender, EventArgs e)
{
empCode = txtCode.Text;
empName = txtName.Text;
empCell = txtCell.Text;
empAddress = txtAddress.Text;
try
{
using (cmd = new SqlCommand(" empInsert ", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#empcode", SqlDbType.VarChar).Value = empCode;
cmd.Parameters.Add("#empname", SqlDbType.VarChar).Value = empName;
cmd.Parameters.Add("#empcell", SqlDbType.VarChar).Value = empCell;
cmd.Parameters.Add("#empaddress", SqlDbType.VarChar).Value = empAddress;
conn.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("succesfully inserted", "Congrates");
}
catch (Exception ex)
{
MessageBox.Show("can't Insert there is error :" + ex, "Error");
}
finally
{
conn.Close();
}
}
Here is Stored procedure on SQL DB side.
use GDK
GO
create PROCEDURE dbo.empInsert
#id as VARCHAR(10,
#name as VARCHAR(10),
#cell as VARCHAR(10),
#address as VARCHAR(20)
AS
BEGIN
INSERT INTO EmployeeRecord(empcode,empname,empcell,empaddress) VALUES( #id, #name, #cell, #address)
END
I am unable to INSERT in DB.
Kindly help in this regard
You have parameter name #id in stored procedure but you are passing #empcode
Change
cmd.Parameters.Add("#empcode", SqlDbType.VarChar).Value = empCode;
To
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = empCode;
The problem is that your parameter names do not match.
From MSDN:
When using parameters with a SqlCommand to execute a SQL Server stored
procedure, the names of the parameters added to the Parameters
collection must match the names of the parameter markers in the stored
procedure.
So this is what you need:
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", empCode);
cmd.Parameters.AddWithValue("#name", empName);
cmd.Parameters.AddWithValue("#cell", empCell);
cmd.Parameters.AddWithValue("#address", empAddress);
I have an update stored procedure which works perfectly on my sql , yet when I try to update on my c# form it doesn't update , yet my code seems to be right , im not sure why cant I perform an update
this is my update stored procedure
sql script
USE [MediaPlayer]
GO
/* Object: StoredProcedure [dbo].[updateBooks] Script Date: 11/25/2013 07:51:33 */
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[updateBooks]
-- Add the parameters for the stored procedure here
#Name nvarchar (50),
#FileName nvarchar(50),
#FilePath nvarchar(50),
#FileSize float,
#DateAdded date,
#MediaLength nvarchar (50),
#MediaSubType nvarchar (50),
#MediaType nvarchar (50),
#Thumbnail image,
#DateAquired datetime,
#BooksName nvarchar (50),
#Publisher nvarchar(50),
#Author nvarchar(50),
#YearOfPublication date,
#Genre nvarchar (50),
#ISBN nvarchar (50),
#Synoposis nvarchar(max),
#SeriesTitle nvarchar(50),
#SeriesNumber nvarchar (50),
#BookCover image,
#GeneralID int output,
#BookID int output
AS
BEGIN
update dbo.Book
SET
BooksName=#BooksName,
Publisher=#Publisher,
Author =#Author,
[Year of publication] =#YearOfPublication,
Genre =#Genre,
ISBN=#ISBN,
Synoposis=#Synoposis,
[Series Title]= #SeriesTitle,
[Series Number] =#SeriesNumber,
[Book Cover] =#BookCover
from Book
Where BookID = #BookID
select ##ROWCOUNT
update dbo.General
SET
Name =#Name,
FileName= #FileName,
FilePath= #FilePath,
FileSize=#FileSize,
DateAdded= #DateAdded,
MediaLength =#MediaLength,
MediaSubType = #MediaSubType,
MediaType = #MediaType,
Thumbnail =#Thumbnail,
DateAquired= #DateAquired
where GeneralID = #GeneralID
END
C# code
private void DoUpdate()
{
try
{
string picLoc = "C:\\Users\\Dee\\Pictures\\PIC\\download.jpg";
try
{
byte[] img = null;
FileStream fs = new FileStream(picLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string connectionString = "Data Source=(local);Initial Catalog=MediaPlayer;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.updateBooks", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", SqlDbType.NVarChar).Value = NametextBox.Text.ToString();
cmd.Parameters.AddWithValue("#FileName", SqlDbType.NVarChar).Value = FileNametextBox.Text.ToString();
cmd.Parameters.AddWithValue("#FileSize", SqlDbType.Float).Value = Convert.ToDouble(fileSizetextBox.Text);
cmd.Parameters.AddWithValue("#FilePath", SqlDbType.NVarChar).Value = FilePathtextBox.Text.ToString();
cmd.Parameters.AddWithValue("#DateAdded", SqlDbType.Date).Value = DateAddeddateTimePicker.Text.ToString();
cmd.Parameters.AddWithValue("#MediaLength", SqlDbType.NVarChar).Value = MediaLengthtetextBox.Text.ToString();
cmd.Parameters.AddWithValue("#MediaSubType", SqlDbType.NVarChar).Value = MediaSubtypetextBox.Text.ToString();
cmd.Parameters.AddWithValue("#MediaType", SqlDbType.NVarChar).Value = MediaTypetextBox.Text.ToString();
cmd.Parameters.Add(new SqlParameter("#Thumbnail", img));
cmd.Parameters.AddWithValue("#DateAquired", SqlDbType.DateTime).Value = DateAquiredDatetimepicker.Text.ToString();
cmd.Parameters.AddWithValue("#Author", SqlDbType.NVarChar).Value = AuthortextBox.Text.ToString();
cmd.Parameters.AddWithValue("#Publisher", SqlDbType.NVarChar).Value = PublishertextBox.Text.ToString();
cmd.Parameters.AddWithValue("#BooksName", SqlDbType.NVarChar).Value = BooksNametextBox.Text.ToString();
cmd.Parameters.AddWithValue("#SeriesTitle", SqlDbType.Date).Value = SeriesTitletextBox.Text.ToString();
cmd.Parameters.AddWithValue("#SeriesNumber", SqlDbType.NVarChar).Value = SeriesNumberTextBox.Text.ToString();
cmd.Parameters.AddWithValue("#Genre", SqlDbType.NVarChar).Value = genretextBox.Text.ToString();
cmd.Parameters.AddWithValue("#Synoposis", SqlDbType.NVarChar).Value = SynoposistextBox.Text.ToString();
cmd.Parameters.AddWithValue("#YearOfPublication", SqlDbType.NVarChar).Value = YearOfPublicationdatetimepicker.Text.ToString();
cmd.Parameters.AddWithValue("#ISBN ", SqlDbType.NVarChar).Value = ISBNtextBox.Text.ToString();
cmd.Parameters.Add(new SqlParameter("#BookCover", img));
SqlParameter parm1 = new SqlParameter("#GeneralID", SqlDbType.Int);
parm1.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parm1);
SqlParameter parm = new SqlParameter("#BookID", SqlDbType.Int);
parm.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parm);
//cmd.ExecuteNonQuery();
MessageBox.Show(cmd.ExecuteNonQuery().ToString() + " record(s) Updated.");
// MessageBox.Show("record successfully updated!");
//clrtxtb();
conn.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (ArgumentException ex)
{
MessageBox.Show("error is " + ex.Message);
}
}
finally
{ }
}
enter code here
What about first uncommenting the line cmd.ExecuteNonQuery(); ?
hi have you tried something like this
SqlConnection sqlConnection = new SqlConnection();
SqlCommand sqlCommand = new SqlCommand();
sqlConnection.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=True";
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "SPName";
sqlCommand.Parameters.Add("#param1", SqlDbType.VarChar).Value = value1;
sqlCommand.Parameters.Add("#param2", SqlDbType.VarChar).Value = value2;
sqlCommand.Parameters.Add("#Param3", SqlDbType.VarChar).Value = value3;
sqlCommand.ExecuteNonQuery();
The two WHERE clauses in stored procedures use the parameters #BookID and #GeneralID.
Because of this, both are supposed to contain a value when the stored procedure is called.
Instead, no value is passed to those parameters. Furthermore, both are declared as OUTPUT.
That's the reason why nothing is updated.
I am trying to insert a parameter through an aspx page via text box. I set my parameters up, but evertime I executenonquery, the #Username shows up in the database instead of the actual value.
Below is my code. Can anyone shed a little insight?
This is the full code:
protected void btn_SubmitUserInfo_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Documents and Settings\\xm\\My Documents\\Visual Studio 2010\\Projects\\CreateUser\\CreateUser\\App_Data\\UserInformation.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
//Open the connection outside of the try statement
conn.Open();
try
{
//Create a command for the stored procedure and tie it into the connection
SqlCommand cmd = new SqlCommand("InsertUserValues", conn);
//Set the command type so it know to execute the stored proc
cmd.CommandType = CommandType.StoredProcedure;
//Declare Parameters
SqlParameter #UserID = new SqlParameter("#UserID", System.Data.SqlDbType.Int);
#UserID.Direction = ParameterDirection.Input;
#UserID.Value = txtUserID.Text;
SqlParameter #UserName = new SqlParameter("#UserName", System.Data.SqlDbType.VarChar);
#UserName.Direction = ParameterDirection.Input;
#UserName.Value = txtUserName.Text;
SqlParameter #UserPassword = new SqlParameter("#UserPassword", System.Data.SqlDbType.VarChar);
#UserPassword.Direction = ParameterDirection.Input;
#UserPassword.Value = txtPassword.Text;
SqlParameter #FirstName = new SqlParameter("#FirstName", System.Data.SqlDbType.VarChar);
#FirstName.Direction = ParameterDirection.Input;
#FirstName.Value = txtFirstName.Text;
SqlParameter #LastName = new SqlParameter("#LastName", System.Data.SqlDbType.VarChar);
#LastName.Direction = ParameterDirection.Input;
#LastName.Value = txtLastName.Text;
SqlParameter #Address = new SqlParameter("#Address", System.Data.SqlDbType.VarChar);
#Address.Direction = ParameterDirection.Input;
#Address.Value = txtAddress.Text;
SqlParameter #AptNum = new SqlParameter("#AptNum", System.Data.SqlDbType.VarChar);
#AptNum.Direction = ParameterDirection.Input;
#AptNum.Value = txtAptNumber.Text;
SqlParameter #City = new SqlParameter("#City", System.Data.SqlDbType.VarChar);
#City.Direction = ParameterDirection.Input;
#City.Value = txtCity.Text;
SqlParameter #State = new SqlParameter("#State", System.Data.SqlDbType.VarChar);
#State.Direction = ParameterDirection.Input;
#State.Value = txtState.Text;
//SqlParameter #Zip = new SqlParameter("#Zip", System.Data.SqlDbType.Int);
//#Zip.Direction = ParameterDirection.Input;
//#Zip.Value = Convert.ToInt32(txtZip.Text);
//add new parameter command to object
cmd.Parameters.Add(#UserID);
cmd.Parameters.Add(#UserName);
cmd.Parameters.Add(#UserPassword);
cmd.Parameters.Add(#FirstName);
cmd.Parameters.Add(#LastName);
cmd.Parameters.Add(#Address);
cmd.Parameters.Add(#AptNum);
cmd.Parameters.Add(#City);
cmd.Parameters.Add(#State);
//cmd.Parameters.Add(#Zip);
//execute nonquery
cmd.ExecuteNonQuery();
}
finally
{
lblSucess.Text = "Your information has been submitted";
//Close the connection
if (conn != null)
{
conn.Close();
}
}
This is the stored Procedure:
ALTER PROCEDURE dbo.InsertUserValues
#UserID int,
#UserName varchar(50),
#UserPassword varchar(100),
#FirstName varchar(50),
#LastName varchar(50),
#Address varchar(50),
#AptNum varchar(50),
#City varchar(50),
#State varchar(50)
AS
INSERT INTO tb_User( user_Name, password, f_Name, l_Name, address, apt_Number, city, state)
VALUES ( '#UserName', '#UserPassword', '#FirstName', '#LastName', '#Address', '#AptNum', '#City', '#State')
You have your parameter quoted in your SQL statement. Remove the single quotes from around the parameters in your stored procedure definition. Quoting them treats them as literal strings instead of parameters to be replaced.
ALTER PROCEDURE dbo.InsertUserValues
#UserID int,
#UserName varchar(50),
#UserPassword varchar(100),
#FirstName varchar(50),
#LastName varchar(50),
#Address varchar(50),
#AptNum varchar(50),
#City varchar(50),
#State varchar(50)
AS
INSERT INTO tb_User( user_Name, password, f_Name, l_Name, address, apt_Number, city, state)
VALUES (#UserName, #UserPassword, #FirstName, #LastName, #Address, #AptNum, #City, #State)
Your parameter name is not correct - you shouldn't use # in the beginning of C# variables. It should be:
SqlParameter UserName = new SqlParameter("#UserName", System.Data.SqlDbType.VarChar);
UserName.Direction = ParameterDirection.Input;
UserName.Value = txtUserName.Text;
cmd.Parameters.Add(UserName);
I don't think it's the root of your problem but that's just something I noticed.
We need more code to see what's the problem