I'm trying to make an insert from my controller to my database. I already debug and it never enter on the exception. But i can not see the values on the db.
This is my sp:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[RegisterUser]
-- Add the parameters for the stored procedure here
#Username nvarchar(10),
#Password nvarchar(10),
#Mail nvarchar(10),
#Birthday date
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Users
(
Username,
Pass,
Mail,
Birthday
)
VALUES
(
#Username,
#Password,
#Mail,
#Birthday
)
END
And on my model i used this method:
public bool registerUser(UserModel user)
{
bool isOk = false;
using (SqlConnection connection = DbConnection.OpenConnection2())
{
try
{
using (SqlCommand command = new SqlCommand("RegisterUser", connection))
{
command.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(command);
command.Parameters.Add(new SqlParameter("#UserName", SqlDbType.VarChar)).Value = user.userName.Trim();
command.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar)).Value = user.password.Trim();
command.Parameters.Add(new SqlParameter("#Mail", SqlDbType.VarChar)).Value = user.mail.Trim();
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
}
finally
{
if (connection.State.Equals(ConnectionState.Open))
{
connection.Close();
isOk = true;
}
}
}
return isOk;
}
Any ideas of why this is not working?
Thanks
Things are easy, if you use exception handling in a proper manner. You are swallowing the exception thrown by Ado.net. Follow these steps for solving your problem:
First of all you should add a throw statement in your catch block to get the exception being thrown. In production, You should catch that at later calling function or layer.
You need to provide all the parameters to your stored procedure. Currently, You are not passing one parameter named #Birthday and its value. Add this parameter with its value.
Here is the modified code that should work.
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#UserName", SqlDbType.VarChar)).Value = user.userName.Trim();
command.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar)).Value = user.password.Trim();
command.Parameters.Add(new SqlParameter("#Mail", SqlDbType.VarChar)).Value = user.mail.Trim();
//Assuming that the user object has a field named Birthday
command.Parameters.Add(new SqlParameter("#Birthday", SqlDbType.Date)).Value = user.Birthday;
command.ExecuteNonQuery();
If you follow my first advice, you will nearly get any other problem that is occurring in your code.
I hope it will help you somehow. Thanks!
If you prefer, you can provide a default value for the parameter #Birthday as:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[RegisterUser]
-- Add the parameters for the stored procedure here
#Username nvarchar(10),
#Password nvarchar(10),
#Mail nvarchar(10),
#Birthday date = NULL
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Users
(
Username,
Pass,
Mail,
Birthday
)
VALUES
(
#Username,
#Password,
#Mail,
#Birthday
)
END
If you are not supplying "#Birthday" parameter, Please specify "#Birthday date" as "#Birthday date = NULL" in the stored procedure as below:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[RegisterUser]
-- Add the parameters for the stored procedure here
#Username nvarchar(10),
#Password nvarchar(10),
#Mail nvarchar(10),
#Birthday date = NULL
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Users
(
Username,
Pass,
Mail,
Birthday
)
VALUES
(
#Username,
#Password,
#Mail,
#Birthday
)
END
Rest of your code looks all good to me.
Hope this will help you.
Related
[SCHOOL WORK]
I have a stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [IO].[usp_selectUser] (#username varchar(50))
AS
BEGIN
SELECT passwordSalt, hashedPassword
FROM [IO].[Users]
WHERE username = #username;
END
And in my C# program I need to get the passwordSalt and the hashedPassword where username matches:
Current C# code:
SqlCommand command = new SqlCommand("[IO].[usp_selectUser]", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#username", SqlDbType.VarChar)).Value = username;
I've tried some stuff from Google search results, but none of the worked properly. How do I get two individual strings?
A friend solved my problem. The stored procedure didn’t have marked parameters as output.
USE [TICKETING_DB]
GO
/****** Object: StoredProcedure [IO].[usp_selectUser] Script Date: 5/4/2020 11:08:10 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [IO].[usp_selectUser] (#username varchar(50), #passwordSalt varchar(50) output, #hashedPassword varchar(100) output)
AS
BEGIN
SELECT #passwordSalt = passwordSalt, #hashedPassword = hashedPassword FROM [IO].[Users]
WHERE username = #username;
END
hello friends i face one issue for load the data to grid view.
the page load event call the one method like loaddata() inside i write the code this
using (SqlConnection Sqlcon = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
Sqlcon.Open();
cmd.Connection = Sqlcon;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SP_Marketing";
//cmd.Parameters.Add(new SqlParameter("#Sno", (object) ?? null.Value));
cmd.Parameters.Add(new SqlParameter("#pvchAction", SqlDbType.VarChar,50));
cmd.Parameters["#pvchAction"].Value = "select";
cmd.Parameters.Add("#pIntErrDescOut", SqlDbType.Int).Direction = ParameterDirection.Output;
SqlAda = new SqlDataAdapter(cmd);
ds = new DataSet();
SqlAda.Fill(ds);
GridViewSample.DataSource = ds;
GridViewSample.DataBind();
}
}
the find the store procedure records in sqlada caught error like"Procedure or function expects parameter #dateemailed which is not supplied"
ALTER PROCEDURE SP_Marketing
(
#Sno int =0,
#DateEmailed datetime,
#DateResponded datetime,
#EmailRep varchar(100)=null,
#Type varchar(100)=null,
#Country varchar(100)=null,
#State varchar(100)=null,
#NameoftheCompany varchar(100)=null,
#website varchar(100)=null,
#FirstName varchar(100)=null,
#LastName varchar(100)=null,
#Title varchar(100)=null,
#Email varchar(100)=null,
#Telephone varchar(100)=null,
#Capabilities varchar(100)=null,
#Focus varchar(100)=null,
#pvchCreatedBy varchar(100)=null,
#pvchAction varchar(50)=null,
#pIntErrDescOut int output
)
AS
BEGIN
if(#pvchAction='select')
begin
SELECT sno,Dateemailed,dateresponded,emailrep,[type],country,[state], , nameofthecompany,website,Firstname,Lastname,Title,email,telephone,
capabilities, Focus FROM Emailmarketing WHERE active=1
end
else if(#pvchAction='insert')
begin
INSERT INTO EmailMarketing(DateEmailed,DateResponded,EmailRep,[Type],
Country,[State],NameoftheCompany,website,FirstName,LastName,Title,Email,Telephone,Capabilities,Focus,Createdby,CreatedDt,Active)VALUES(#DateEmailed,#DateResponded,#EmailRep,#Type,
#Country,#State,#NameoftheCompany,#website,#FirstName,#LastName,#Title,#Email,#Telephone,#Capabilities,#Focus,#pvchCreatedBy,GETDATE(),1);
end
else if(#pvchAction='update')
begin
UPDATE EmailMarketing SET DateEmailed=#DateEmailed,DateResponded=#DateResponded,EmailRep=#EmailRep,[Type]=#Type,Country=#Country,[State]=#State,NameoftheCompany=#NameoftheCompany,website=#website,FirstName=#FirstName,LastName=#LastName,Title=#Title,Email=#Email,Telephone=#Telephone,Capabilities=#Capabilities,Focus=#Focus,Updatedby=#pvchCreatedBy,UpdatedDt=GETDATE()
WHERE Sno=#Sno;
end
else if(#pvchAction='delete')
begin
UPDATE EmailMarketing SET Active=#pvchAction WHERE Sno=#Sno;
end
IF (##ERROR <> 0)
BEGIN
SET #pIntErrDescOut = 1
END
ELSE
BEGIN
SET #pIntErrDescOut = 0
END
END
The following parameters don't have default values in your stored proc:
#DateEmailed datetime,
#DateResponded datetime,
So you always need to provide those values in the code:
cmd.Parameters.Add(new SqlParameter("#DateEmailed", SqlDbType.DateTime));
cmd.Parameters["#DateEmailed"].Value = DateTime.Now; // Provide your value here
cmd.Parameters.Add(new SqlParameter("#DateResponded", SqlDbType.DateTime));
cmd.Parameters["#DateResponded"].Value = DateTime.Now; // Provide your value here
If you are calling a stored procedure, in addition to the NULL issue someone mentioned above, there is a type mismatch issue. For instance I was getting the "Expects parameter that is not supplied" error, when I was supplying the parameter.
After pulling my hair out for a while I found that the procedure had an input parameter of nvarchar(50) and I was passing a string that was longer than that. Apparently any kind of mismatch is reported the same as not providing (which in a way I suppose it is).
So you may want to double check data types and sizes on both ends.
I have the following Stored procedure
ALTER PROCEDURE dbo.USER_AUTH
(
#username varchar,
#password varchar
)
AS
BEGIN
SELECT * FROM users
WHERE username = #username
AND password = #password;
END
And there are Two rows in the users table.
This gives an empty reader error
_Command = new SqlCommand("[dbo].[USER_AUTH]", _Connection);
_Command.CommandType = System.Data.CommandType.StoredProcedure;
_Command.Parameters.AddWithValue("#username", _Username);
_Command.Parameters.AddWithValue("#password", _Password);
reader = _Command.ExecuteReader();
While this works fine
_Command = new SqlCommand("select * from users where
username=#username and password=#password" , _Connection);
_Command.Parameters.AddWithValue("#username", _Username);
_Command.Parameters.AddWithValue("#password", _Password);
reader = _Command.ExecuteReader();
Where _Connection is SqlConnection _Connection , _Command is SqlCommand _Command and
reader is SqlDataReader
This happens because your stored procedure declares
ALTER PROCEDURE dbo.USER_AUTH
(
#username varchar,
#password varchar
)
without specifying a size for the two varchars. In this way just one char is passed to the parameters and of course nothing is retrieved
Change the sp to
ALTER PROCEDURE dbo.USER_AUTH
(
#username nvarchar(30),
#password nvarchar(30)
)
or whatever size are your two database fields
You have to specify the length for varchar
So if we don't specify the length ourself these are the default values SQL Server uses - which means the data what we would be expecting to get stored in the database would have got silently truncated without our knowledge.
Bad habits to kick : declaring VARCHAR without (length)
ALTER PROCEDURE dbo.USER_AUTH
(
#username varchar(20),
#password varchar(20)
)
AS
BEGIN
SELECT * FROM users
WHERE username = #username
AND password = #password;
END
I am trying to write procedure for insert value into table but the value not inserted in table
for reference I am give code which i had try for it...can anyone please help me
for insert i am try this code
public int Visitor_Insert(visitor_Master visitor_obj, common_Class comm_obj)
{
DB_Connection();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT_VISITOR";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#VISITOR_NAME", visitor_obj.VisitorName);
cmd.Parameters.AddWithValue("#VISITOR_CONTACT", visitor_obj.VisitorContact);
cmd.Parameters.AddWithValue("#VISITOR_ADDRESS", visitor_obj.VisitorAddress);
cmd.Parameters.AddWithValue("#VISITOR_AGE", visitor_obj.VisitorAge);
cmd.Parameters.AddWithValue("#VISITOR_VEHICLENO", visitor_obj.VisitorVehicleNO);
//cmd.Parameters.AddWithValue("#VISITOR_AGE ", visitor_obj.VisitorAge);
int i = cmd.ExecuteNonQuery();
return i;
}
For Procedure I am written this code
USE [VPMS]
GO
/****** Object: StoredProcedure [dbo].[INSERT_VISITOR] Script Date: 07/24/2013 16:01:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[INSERT_VISITOR]
#VISITOR_NAME NVARCHAR(30),
#VISITOR_CONTACT NVARCHAR(10),
#VISITOR_ADDRESS NVARCHAR(40),
#VISITOR_AGE NVARCHAR(2),
#VISITOR_VEHICLENO NVARCHAR(20),
#VISITOR_IMAGE IMAGE,
#VISITOR_CREATEDBY NVARCHAR(20),
#VISITOR_CREDTEDON NVARCHAR(20),
#VISITOR_MODIFIEDBY NVARCHAR(20),
#VISITOR_MODIFIEDON NVARCHAR(20)
AS
DECLARE #VISITOR_ID INT,
BEGIN
SET NOCOUNT ON;
SELECT #VISITOR_ID= MAX(Visitor_Id) FROM Visitor_Master
IF (#VISITOR_ID > 0 )
BEGIN
SET #VISITOR_ID=#VISITOR_ID+1
END
ELSE
BEGIN
SET #VISITOR_ID=10
END
INSERT INTO Visitor_Master( Visitor_Id, VisitorName, Visitor_Contact, Visitor_Address, Visitor_age,
Visitor_VehicleNo, Visitor_Image, Created_By, Created_On, Modify_By, Modify_On)
VALUES(#VISITOR_ID,#VISITOR_NAME,#VISITOR_CONTACT,#VISITOR_ADDRESS,#VISITOR_AGE,#VISITOR_VEHICLENO,#VISITOR_IMAGE,#VISITOR_CREATEDBY,
#VISITOR_CREDTEDON,#VISITOR_MODIFIEDBY,#VISITOR_MODIFIEDON)
END
As you are not passing all the parameters defined in the procedure. It will throw exception.
Here I have assigned null to other parameters which you have not specified assign value as per your reqirement
ALTER PROCEDURE [dbo].[INSERT_VISITOR]
#VISITOR_NAME NVARCHAR(30),
#VISITOR_CONTACT NVARCHAR(10),
#VISITOR_ADDRESS NVARCHAR(40),
#VISITOR_AGE NVARCHAR(2),
#VISITOR_VEHICLENO NVARCHAR(20),
#VISITOR_IMAGE IMAGE = null,
#VISITOR_CREATEDBY NVARCHAR(20) = null,
#VISITOR_CREDTEDON NVARCHAR(20) = null,
#VISITOR_MODIFIEDBY NVARCHAR(20) = null,
#VISITOR_MODIFIEDON NVARCHAR(20) = null
-- rest of code
You have #VISITOR_IMAGE,#VISITOR_CREATEDBY,#VISITOR_CREDTEDON,#VISITOR_MODIFIEDBY,#VISITOR_MODIFIEDON parameters in your procedure but you have not passed value to the the above parameter.Either pass value to all the parameters or allow null
BEGIN
set #VISITOR_IMAGE = null,
set #VISITOR_CREATEDBY = null,
set #VISITOR_CREDTEDON = null,
set #VISITOR_MODIFIEDBY = null,
set #VISITOR_MODIFIEDON = null
........
I used the following statement for a parameter.
comm.Parameters.Add("#name", SqlDbType.NVarChar, 50).Value = txtname.Text;
Name is a SQL Server nvarchar column but I get this error:
Error converting data type nvarchar to numeric.
My sql:
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "execute addName #name";
comm.Parameters.Add("#name", SqlDbType.NVarChar, 50).Value = txtname.Text;
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
Can help my to fix this problem?
My store procedure:
USE [info]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[addName]
#id numeric(18,0) = 0,
#name nchar(50)
as
if (select name from TName where name = #name) is null
begin
select #id = MAX(id)+1 from TName
insert into TName
values (#id, #name)
print #id
end
else
begin
print 'Eroare'
end
With the edit, with the signature:
ALTER procedure [dbo].[addName]
#id numeric(18,0) = 0,
#name nchar(50)
then the problem becomes clear:
execute addName #name
is pass-by-position - so you are passing the value of #name into the #id parameter. If you were calling this from TSQL, to pass-by-name you need to use:
execute addName #name = #name
The first (left) states the parameter name, the second (right) states the value to use for this parameter; for example, to pass a literal into addName's #name parameter:
execute addName #name = 'Fred'
However, from ADO.NET, a better approach is:
comm.CommandText = "addName";
comm.CommandType = CommandType.StoredProcedure;
which automatically treats it as an SP-exec using pass-by-name.
You must modify the type of your parameter name in your addName procedure, and set to NVarChar
You pass in C# NVarChar type, but you have numeric who is asked in procedure