'System.Data.SqlClient.SqlException' thrown - c#

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

Related

How to set SQL Server procedure variables to inputted data from C# ASP.NET MVC program?

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();

Procedure or function 'TestTableInsert' expects parameter '#EDIPI', which was not supplied

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

C# can't insert into Data Source

Here is my code:
try
{
SqlCommand cmd2 = new SqlCommand(#"INSERT INTO Clienti (parola,nume,prenume,adresa,email,kcal_zilnice) VALUES (#Parola,#Nume,#Prenume,#Adresa,#Email,2000)", conn);
cmd2.Prepare();
cmd2.Parameters.AddWithValue("#Parola", passBox.Text);
cmd2.Parameters.Add("#Nume", SqlDbType.VarChar, 50).Value = nameBox.Text;
cmd2.Parameters.Add("#Prenume", SqlDbType.VarChar, 50).Value = pnameBox.Text;
cmd2.Parameters.Add("#Adresa", SqlDbType.VarChar, 100).Value = adressBox.Text;
cmd2.Parameters.Add("#Email", SqlDbType.VarChar, 100).Value = emailBox.Text;
cmd2.ExecuteNonQuery();
}
catch (SqlException exception)
{
MessageBox.Show("Failed! " + exception.Message);
}
MessageBox.Show("User Created!");
I don't know what am I doing wrong here. I even tried to replace #Parola with 'abc' but it does not work. I don't get any error message. Every time I get "User Created", but when I look into the DB I get all the fields NULL(no records where created).
So, for anyone that has the same problem Prepare() solved it.
Use Add() for params and specify The SqlDbType. Prepare() will not work with AddWithValue().
At the end do Prepare() and then ExecuteNonQuery().

The name '"' does not exist in the current context

I am facing several errors in my code. These errors are:
Error 17 The name 'CommandType' does not exist in the current context
Error 18 The name 'SqlDbType' does not exist in the current context
Error 35 The name 'txtCity' does not exist in the current context
I would like if you can help me to understand the error and tell me how I can fix it.
protected void btnSave_Click(object sender, EventArgs e)
{
// create connectionstring and insert statment
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string insertSql = " INSERT INTO UserInfo (UID, FN, LN, Password, RePass, Email, Country,State, City)" +
" values (#UsrNme, #fnbox, #lnamebox, #passtxtbx1, #passtxtbx2, #emailbox, #DrDncoundrlst, #DropDownListSwestate, #citytxtbox)";
// create SQL Connection
SqlConnection con = new SqlConnection(connectionString);
// create sql command and parameters
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.text;
cmd.CommandText = insertSql;
SqlParameter UID = new SqlParameter("#UsrNme", SqlDbType.nvarchar, 50);
UID.Value = txtUID.text.tostring();
cmd.Parameters.Add(UID);
SqlParameter FN = new SqlParameter("#fnbox", SqlDbType.varchar,25);
cmd.Connection = con;
FN.Value = txtfn.text.ToString();
cmd.Parameters.Add(FN);
SqlParameter LN = new SqlParameter("#lnamebox", SqlDbType.varchar, 25);
cmd.Connection = con;
LN.Value = txtLN.text.ToString();
cmd.Parameters.Add(LN);
SqlParameter Password = new SqlParameter("#passtxtbx1", SqlDbType.varchar, 25);
cmd.Connection = con;
Password.Value = txtPassword.text.ToString();
cmd.Parameters.Add(Password);
SqlParameter RePass = new SqlParameter("#passtxtbx2", SqlDbType.varchar, 25);
cmd.Connection = con;
RePass.Value = txtRePass.text.ToString();
cmd.Parameters.Add(RePass);
SqlParameter Email = new SqlParameter("#emailbox", SqlDbType.varchar, 25);
cmd.Connection = con;
Email.Value = txtEmail.text.ToString();
cmd.Parameters.Add(Email);
SqlParameter Country = new SqlParameter("#DrDncoundrlst", SqlDbType.varchar, 25);
cmd.Connection = con;
Country.Value = txtCountry.text.ToString();
cmd.Parameters.Add(Country);
SqlParameter State = new SqlParameter("#DropDownListSwestate", SqlDbType.varchar, 25);
cmd.Connection = con;
State.Value = txtState.text.ToString();
cmd.Parameters.Add(State);
SqlParameter City = new SqlParameter("#citytxtbox", SqlDbType.varchar, 25);
cmd.Connection = con;
City.Value = txtCity.text.ToString();
cmd.Parameters.Add(City);
try
{
con.Open();
cmd.ExecuteNonQuery();
lblmsg.Text = "You already complete your registration process";
}
catch (SqlException ex)
{
string errorMessage = "error in registration user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
con.Close();
}
}
You may be way over-complicating things. Try the following code...
var connection = new SqlConnection(connectionString);
var cmd = new SqlCommand(insertSql, connection);
cmd.Parameters.AddWithValue("#UsrNme", txtUID.Text.ToString());
cmd.Parameters.AddWithValue("#fnbox", txtfn.Text.ToString());
cmd.Parameters.AddWithValue("#lnamebox", txtLN.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx1", txtPassword.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx1", txtPassword.Text.ToString());
cmd.Parameters.AddWithValue("#passtxtbx2", txtRePass.Text.ToString());
cmd.Parameters.AddWithValue("#emailbox", txtEmail.Text.ToString());
cmd.Parameters.AddWithValue("#DrDncoundrlst", txtCountry.Text.ToString());
cmd.Parameters.AddWithValue("#DropDownListSwestate", txtState.Text.ToString());
cmd.Parameters.AddWithValue("#citytxtbox", txtCity.Text.ToString());
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
lblmsg.Text = "You already completed your registration process";
}
catch (SqlException ex)
{
var errorMessage = "error in registration user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
con.Close();
}
You also want to make sure the you have the following using clauses declared...
using System.Data;
using System.Data.SqlClient;
... and that txtCity is what you actually called your text box and that it's not hidden from this method by a private identifier or actually appears on a different form because the error you're getting means that the variable is outside the method's scope or has its lifetime expire before you reach this method.
Here's what all that code does. Instead of setting up tons of metadata that you should not need to declare your parameters, it lets SqlCommand do all the hard work for you and figure out what type is what based on the database column, the type of the object you passed in, and the name of the parameter. If you end up allowing the passing of invalid data, none of the elaborate metadata markup is going to save you from an error.
Likewise, you really want to look into wrapping your insertSql into a stored procedure like so in Sql Server...
create procedure adduserinfo #UsrNme nvarchar (50),
#fnbox varchar (25),
#lnamebox varchar (25),
#passtxtbx1 varchar (25),
#passtxtbx2 varchar (25),
#emailbox varchar (25),
#DrDncoundrlst varchar (25),
#DropDownListSwestate varchar (25),
#citytxtbox varchar (25)
as begin
INSERT INTO UserInfo
( UID,
FN,
LN,
Password,
RePass,
Email,
Country,
State,
City )
VALUES
( #UsrNme,
#fnbox,
#lnamebox,
#passtxtbx1,
#passtxtbx2,
#emailbox,
#DrDncoundrlst,
#DropDownListSwestate,
#citytxtbox )
end
go
Then your SqlCommand declaration would look like so...
var command = new SqlCommand("adduserinfo", connection)
{
CommandType = CommandType.StoredProcedure;
}
... and for the rest you'd follow the rest of the code I provided above. This would be the more or less proper way to do it. And at the risk of sounding nitpicky, consider more informative and consistently formatted variable and parameter names. Those who might have to modify your code in the future will thank you for it.

Passing parameter to stored procedure in C#

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.

Categories

Resources