problem with my C# code in inserting in mysql - c#

kindly let me know how to insert two variables. its not a problem giving directly my userid and mobile in the code like
string insert =#"Insert into userHistory(userid,mobile) values(x,y)";
This is my code, but it fails to insert (editors note: OP provided no error)
int userid = 123456;
long mobile = 91888888888;
sqlConn = new MySqlConnection(/* conn string removed */);
sqlConn.Open();
string insert =
#"Insert into userHistory(userid,mobile) values(#userid,#mobile);";
MySqlCommand cmd = new MySqlCommand(insert,sqlConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new MySqlParameter("#userid", userid));
cmd.Parameters.Add(new MySqlParameter("#mobile", mobile));

Without more Information, I guess the type of your command should be "Text" and not CommandType.StoredProcedure, since you do not execute a SP. And you have to execute the command (maybe this is only missing in your code)

this is wrong cmd.CommandType = CommandType.StoredProcedure the command is should be CommandType.Text
You can read more about the CommandType enumeration here.
There are some more .net examples for MySql here

I think the issue is cmd.CommandType = CommandType.StoredProcedure;
You are trying to execute an ad-hoc query, not a Stored Procedure. Try changing it to
cmd.CommandType = CommandType.Text;

Related

How do I use ExecuteScalar with a stored Procedure?

I'm trying to get a count of column records in a Sql database and show the result in a MessageBox.
This is my code:
public DataTable CheckIfNameExist(string name)
{
con = Connect();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "spCheckIfNameExist";
cmd.Parameters.AddWithValue("#Name", SqlDbType.NVarChar).Value = name;
MessageBox.Show(name);
Int32 totalNames = (Int32) cmd.ExecuteScalar();
string tNames = totalNames.ToString();
MessageBox.Show(tNames);
}
And this is my sp:
#Name nvarchar(50) = null
As
Begin
SELECT COUNT(*) from OrdersSent where CustomerName LIKE #Name + '%'
End
Problem:
It always returns 0.
There are a couple of errors in your code:
You should write it as:
cmd.CommandText = "spCheckIfNameExist";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = name;
First you need to tell the ADO engine that you are calling a stored procedure and not a simple command text, but you also need to use Add instead of AddWithValue to be precise on the type of the parameter passed to the SP. Your code creates a parameter int becase the second parameter of the AddWithValue is the Value of the parameter not the type.
You have a few problems in the c# code - the most important is probably this:
cmd.Parameters.AddWithValue("#Name", SqlDbType.NVarChar).Value = name;
Don't use AddWithValue. Use Add.
Also, you didn't specify the command type - the default is Text.
And you are using fields for SqlConnection and SqlCommand - which is also the wrong thing to do. You should create and dispose both of them inside each method you are using them.
A better version of your code would be this:
using(var con = new SqlConnection(ConnectionString))
{
using(var cmd = new SqlCommand("spCheckIfNameExist", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = name;
con.Open();
var tNames = cmd.ExecuteScalar().ToString();
}
}
Another thing that puzzles me is why a method called CheckIfNameExist returns a DataTable. I would expect it to simply return a bool.
If you really only want to check if the name exists, you can do this better on both the SQL level and the c# level.
A better SQL would be something like this:
SELECT CAST(CASE WHEN EXISTS(
SELECT 1
FROM OrdersSent
WHERE CustomerName LIKE #Name + '%'
) THEN 1 ELSE 0 END AS bit)
And on the c# level, bit translates directly to bool, so the code can simple be this:
public bool CheckIfNameExist(string name)
{
using(var con = new SqlConnection(ConnectionString))
{
using(var cmd = new SqlCommand("spCheckIfNameExist", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = name;
con.Open();
return (bool)cmd.ExecuteScalar();
}
}
}
And another note - you should avoid using the sp prefix for stored procedures.
Microsoft have reserved this prefix for built in system procedures.
For more information, read Aaron Bertrand's Is the sp_ prefix still a no-no?, where you'll see that the short answer to this question is "Yes".
The sp_ prefix does not mean what you think it does: most people think sp stands for "stored procedure" when in fact it means "special." Stored procedures (as well as tables and views) stored in master with an sp_ prefix are accessible from any database without a proper reference (assuming a local version does not exist). If the procedure is marked as a system object (using sp_MS_marksystemobject (an undocumented and unsupported system procedure that sets is_ms_shipped to 1), then the procedure in master will execute in the context of the calling database.
You need to specify the type of your command like this:
cmd.CommandText = "spCheckIfNameExist";
cmd.CommandType = CommandType.StoredProcedure;
See also:
What is the benefit of using CommandType.StoredProcedure versus using CommandType.Text?
Although specify the type directly and use the Value property is more better than AddWithValue:
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = name;
The following article could be also interesting:
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

Teradata query "SHOW PROCEDURE dbName.SP_Name;" not return result

when calling statement "SHOW PROCEDURE dbName.SP_Name;" on Teradata Database thorugh the code (.net) i get back empty result set.
but when i run this query on the SQL ASSISTANT with the same credentials, i do receive results...
please note that every other queries on the DB i do get it with no problem.
it came empty only on "SHOW PROCEDURE" command
this is the code:
using (TdConnection cn = new TdConnection(ConnectionString))
{
cn.Open();
TdCommand cmd = cn.CreateCommand();
cmd.CommandTimeout = CommandTimeoutWindow;
cmd.CommandText = query;
using (TdDataAdapter da = new TdDataAdapter(cmd))
{
da.Fill(dt);
}
}
can you suggest an idea..?
thank you
details:
Teradata DB version: 14.00.07.16
.NET Data Provider for Teradata: Teradata.Client.Provider, Version=16.10.0.0
Please give the command type as command type. Text
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
Also try with an extended connection time out.

Call SQL Server stored procedure with parameters using C#

I am trying to call a very simple SQL Server stored procedure using C# code. I have a class which has authenticate method. I am passing text box values (userID, password) to this method and it keeps on throwing me error about required parameter not being passed. I am basically a Business Intelligence professional working on C# project. Help will be appreciated.
Here is the code I am executing:
sqcon.Open();
SqlCommand cmd = new SqlCommand("Users.PR_Authenticate_WebUsers",sqcon);
cmd.Parameters.Add("#In_UserID", SqlDbType.VarChar).Value = "f";
cmd.Parameters.Add("#In_PassWord", SqlDbType.NVarChar).Value = "f";
cmd.Parameters.Add("#Out_IsAuthenticatedUser", SqlDbType.Bit);
cmd.Parameters["#Out_IsAuthenticatedUser"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
sqcon.Close();
I don't understand when I am passing parameter values explicitly why it complains about value not being passed? Am I missing something?
Hmmm looks like you are not telling the command object that it is a stored procedure not a regular query try this one
sqcon.Open();
SqlCommand cmd = new SqlCommand("Users.PR_Authenticate_WebUsers",sqcon);
cmd.CommandType = CommandType.StoredProcedure;
//Add parameters like this
cmd.Parameters.Add(new SqlParameter("#In_UserID", "f"));
sqcon.Close()

C# Stored procedure or function expects parameter which is not supplied

I am fairly new to C# and I'm trying to set up call to a stored procedure in my database which takes one parameter.
I get the error "Procedure or function 'SP_getName' expects parameter '#username', which was not supplied. "
My Stored procedure works ok when I supply it with the parameter and I run it via SQL management studio.
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[SP_getName]
#username = 'bob101'
SELECT 'Return Value' = #return_value
GO
However when I try and call it the error is with how I'm passing the parameter in, but I can't spot what the issue is.
//create a sql command object to hold the results of the query
SqlCommand cmd = new SqlCommand();
//and a reader to process the results
SqlDataReader reader;
//Instantiate return string
string returnValue = null;
//execute the stored procedure to return the results
cmd.CommandText = "SP_getName";
//set up the parameters for the stored procedure
cmd.Parameters.Add("#username", SqlDbType.NVarChar).Value = "bob101";
cmd.CommandType = CommandType.Text;
cmd.Connection = this.Connection;
// then call the reader to process the results
reader = cmd.ExecuteReader();
Any help in spotting my error would be greatly appreciated!
I've also tried looking at these two posts, but I haven't had any luck:
Stored procedure or function expects parameter which is not supplied
Procedure or function expects parameter, which was not supplied
Thanks!
You have stated:
cmd.CommandType = CommandType.Text;
Therefore you are simply executing:
SP_getName
Which works because it is the first statement in the batch, so you can call the procedure without EXECUTE, but you aren't actually including the parameter. Change it to
cmd.CommandType = CommandType.StoredProcedure;
Or you can change your CommandText to:
EXECUTE SP_getName #username;
As a side note you should Avoid using the prefix 'sp_' for your stored procedures
And a further side note would be to use using with IDisposable objects to ensure they are disposed of correctly:
using (var connection = new SqlConnection("ConnectionString"))
using (var cmd = new new SqlCommand("SP_getName", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#username", SqlDbType.NVarChar).Value = "bob101";
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
// Do something
}
}
}
I had this problem, but it wasn't about parameter name of Command Type.
My problem was that when C# calls SP, for each parameter that has no value passes 'default' keyword (i found it in SQL Profiler):
... #IsStop=0,#StopEndDate=default,#Satellite=0, ...
in my case my parameter Type was DateTime :
#StopEndDate datetime
. I Solved my problem by seting default value to this parameter in Stored Procedure :
#StopEndDate datetime=null
Try remove #:
cmd.Parameters.Add("username", SqlDbType.NVarChar).Value = "bob101";

MySql storedprocedure not executing frm asp.net

I am able to execute MySQL sp. In server it works fine, but when called from asp.net it is not working properly. Below is the stored procedure:
CREATE PROCEDURE `GetCategoryForBackLinkID`(IN BLID int, OUT CatID int)
BEGIN
SELECT CategoryID INTO CatID FROM backlink where BackLinkID = BLID;
END
Below is the asp.net code
MySqlCommand cmd1 = new MySqlCommand("GetCategoryForBackLinkID");
MySqlConnection con1 = new MySqlConnection();
//ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["linkbuilding1Entities3"];
con1.ConnectionString = "server=67.227.183.117;User Id=rammu1;Pwd=eframmu1;database=linkbuilding1;Persist Security Info=True";
cmd1.Connection = con1;
using (cmd1.Connection)
{
cmd1.Connection.Open();
MySqlParameter returnParameter1 = cmd1.Parameters.Add("BLID", MySqlDbType.Int16);
returnParameter1.Direction = ParameterDirection.Input;
returnParameter1.Value = maximumbacklinid;
MySqlParameter returnParameter2 = cmd1.Parameters.Add("CatID", MySqlDbType.Int16);
returnParameter2.Direction = ParameterDirection.Output;
cmd1.ExecuteNonQuery();
CategID = (Int16)returnParameter2.Value;
The error I get is
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'GetCategoryForBackLinkID' at line 1.
What is possibly wrong here?
Well, I'm not 100% sure but looks like you need to assing your CommandType property like;
cmd1.CommandType = CommandType.StoredProcedure;
Since you using store procedure, this property is Text by default. That's why your program thinks your "GetCategoryForBackLinkID" string is a valid SQL query, not a store procedure.
When you set the CommandType property to StoredProcedure, you should
set the CommandText property to the name of the stored procedure. The
command executes this stored procedure when you call one of the
Execute methods.
using(MySqlConnection con1 = new MySqlConnection(connString))
using(MySqlCommand cmd1 = con.CreateCommand())
{
cmd1.CommandType = CommandType.StoredProcedure;
// Add your parameter values.
cmd1.ExecuteNonQuery();
CategID = (int)returnParameter2.Value;
}
IN Your connection string one keyword is wrong write Data source not database there.
"server=67.227.183.117;User Id=rammu1;Pwd=eframmu1;Data Source=linkbuilding1;Persist Security Info=True";

Categories