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
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 created a Class name EmployeeDAta write this code here and i want to Insert Radiobutton value in SQL Database
public static void AddEmployee(Employee employee)
{
string connString = ConfigurationManager.ConnectionStrings["Employee"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
using (conn)
{
SqlCommand cmd = new SqlCommand("ADDEMPLOYEE", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 50).Value = employee.Name;
cmd.Parameters.Add("#FName", SqlDbType.NVarChar, 50).Value = employee.Fname;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 50).Value = employee.Address;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar, 50).Value = employee.Email;
cmd.Parameters.Add("#Mobile", SqlDbType.NVarChar, 50).Value = employee.Mobile;
cmd.Parameters.Add("#Pincode", SqlDbType.NVarChar, 50).Value = employee.Pincode;
cmd.Parameters.AddWithValue("#VB", SqlDbType.Bit).Value = employee.VB;
cmd.Parameters.AddWithValue("#ASP", SqlDbType.Bit).Value = employee.ASP;
cmd.Parameters.AddWithValue("#Gender", SqlDbType.Int).Value = employee.Gender;
conn.Open();
cmd.ExecuteNonQuery();
}
}
add a parameter to your stored procedure call:
cmd.Parameters.AddWithValue("#ValueOfRadioButtonr", SqlDbType.Int).Value = MyRadioButton.Value;
In the stored procedure on the database, make sure you handle the extra parameter.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Companyregister";
cmd.Parameters.AddWithValue("#Company_name", txtname.Text);
cmd.Parameters.AddWithValue("#Register_no", txtreg_no.Text);
cmd.Parameters.AddWithValue("#Type", DropDownList1.Text);
cmd.Parameters.AddWithValue("#Address", txtadrs.Text);
cmd.Parameters.AddWithValue("#Email", txtemail.Text);
cmd.Parameters.AddWithValue("#Contact_no", txtphone.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Register succesful");
}
Stored procedure:
CREATE PROCEDURE [dbo].Companyregister
#Company_name varchar(50),
#Register_no varchar(50),
#Type varchar(50),
#Address varchar(50),
#Email varchar(50),
#Contact_no varchar(50)
AS
insert into company_reg (Company_name, Register_no, Type, Address, Email, Contact_no)
values (#Company_name, #Register_no, #Type, #Address, #Email, #Contact_no)
RETURN 0
Error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: String or binary data would be truncated.
The following error indicates that one or more of your data field is NOT able to fit in the DB field. For eg, may be your address is of 60 characters but your DB size for it is only 50 characters.
String or binary data would be truncated.
To solve this, first check if the data you are inserting complies to the sizes defined in you DB. To catch this more easily, define your parameters to stored procedure as follows:
cmd.Parameters.Add("#Company_name", SqlDbType.VarChar, 50).Value = txtname.Text;
cmd.Parameters.Add("#Register_no", SqlDbType.VarChar, 50).Value = txtreg_no.Text;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 50).Value = DropDownList1.Text;
cmd.Parameters.Add("#Address", SqlDbType.VarChar, 50).Value = txtadrs.Text;
cmd.Parameters.Add("#Email", SqlDbType.VarChar, 50).Value = txtemail.Text;
cmd.Parameters.Add("#Contact_no", SqlDbType.VarChar, 50).Value = txtphone.Text;
A good way to start investigating exceptions is to wrap your code in try/catch blocks. This will allow you to dig down in the Exception and hopefully get a more meaningful description of the error. Submitting the Exception as part of your question will help the community in finding the cause.
Use a try/catch block as follows
try{
// code goes here
}
catch (Exception e) // this block is only entered when an exception is thrown in the try block
{
Console.WriteLine(e.ToString()); // print the exception description to the Console (if console application)
}
As suggested in the comments, try executing the Stored Procedure using the same parameters and see if it's successful.
Try like this,
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.Int).Direction = ParameterDirection.Output; /// this is optional if you declare #ID in your store procedure
cmd.Parameters.Add("#Company_name", SqlDbType.VarChar).Value = txtname.Text;
cmd.Parameters.Add("#Register_no", SqlDbType.VarChar).Value= txtreg_no.Text;
cmd.Parameters.Add("#Type", SqlDbType.VarChar).Value = DropDownList1.Text;
cmd.Parameters.Add("#Address", SqlDbType.VarChar).Value = txtadrs.Text;
cmd.Parameters.Add("#Email", SqlDbType.VarChar).Value = txtemail.Text;
cmd.Parameters.Add("#Contact_no", SqlDbType.VarChar).Value = txtphone.Text;
And check your variable size and name
I have an update query(stored procedure) which is working properly in SQL Server when I execute it.
CREATE PROCEDURE updatestudenthws(#stdid nvarchar(50),#hwid int, #grade float)
AS
UPDATE Table_Exercise_Answer
SET
ExAns_Grade = #grade
WHERE ExAns_Exercise = #hwid AND ExAns_Student = #stdid
but when I run the program it does not have any effect in my table and also I don't have any error.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.VarChar);
cmd.Parameters.Add("#stdid", SqlDbType.VarChar);
cmd.Parameters.Add("#grade", SqlDbType.VarChar);
cmd.Parameters["#hwid"].Value = hwid;
cmd.Parameters["#stdid"].Value = studentid;
cmd.Parameters["#grade"].Value = grade;
cmd.ExecuteNonQuery();
con.Close();
What is my mistake?
How should I do this work?
Use AddWithValue(), so you don't have to provide the type, which allowed you to make the mistake of passing varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();
Your ADO.NET code defining the parameters for the stored procedure is wrong in that you don't define the parameters with their proper datatypes.
Your stored procedure defines:
#stdid nvarchar(50) --> but you define it as varchar
#hwid int --> but you define it as varchar
#grade float --> but you define it as varchar
You need to change your code to this:
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#hwid", SqlDbType.Int); // this needs to be SqlDbType.Int
cmd.Parameters.Add("#stdid", SqlDbType.NVarChar, 50); // this should be SqlDbType.NVarChar and specify its proper length
cmd.Parameters.Add("#grade", SqlDbType.Float); // this needs to be SqlDbType.Float
when you use AddWithValue(), don't you have to provide the type passing like varchar to an int parameter.
con.Open();
SqlCommand cmd = new SqlCommand("updatestudenthws", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#hwid", hwid);
cmd.Parameters.AddWithValue("#stdid", studentid);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
con.Close();
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.