MySql storedprocedure not executing frm asp.net - c#

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";

Related

.Net5 Call stored procedure in MySql with OUT parameter

I'm trying to call a Stored Procedure in MySql that returns a list of rows and with OUT parameter. Code:
using (MySqlConnection conn = new MySqlConnection("server=***;database=***;uid=***;pwd=***;"))
{
conn.Open();
using var command = conn.CreateCommand();
command.CommandText = "CALL p_detail_get";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#FilterJson", JsonConvert.SerializeObject(input));
command.Parameters.Add("#Output", MySqlDbType.Int32);
command.Parameters["#Output"].Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
}
Error:
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 'CALL p_detail_get('{"id":1}', #outParam1);SELECT '' AS '', #outParam1' at line 1
Can you give me an example of the code that can get both - return from procedure and OUT parameter?

insert value from TextBox into sql

I'm getting this error message: Cannot insert the value NULL into column 'id', table ''; column does not allow nulls. INSERT fails. thanks in advance
protected void AddItem(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO Picture (Album, id) VALUES (#Album, #id)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
}
I suppose that ID is an IDENTITY column. Its value is generated automatically by the database engine and you want to know what value has been assigned to your record.
Then you should change your query to
string insertCmd = #"INSERT INTO Picture (Album) VALUES (#Album);
SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
int newID = Convert.ToInt32(myCommand.ExecuteScalar());
}
The query text now contains a second instruction SELECT SCOPE_IDENTITY() separated from the first command by a semicolon. SCOPE_IDENTITY returns the last IDENTITY value generated for you by the database engine in the current scope.
Now the command is run using the ExecuteScalar to get back the single value returned by the last statement present in the query text without using any output parameter
I would think that ID is identity. You don't have to add this value. I would try the following code and check the database if you get automatically an ID.
string insertCmd = "INSERT INTO Picture (Album) VALUES (#Album)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.ExecuteNonQuery();
}
I case you want to set the id yourself(withoud automatic increment from the db), you should change the schema of the database removing identity from ID as shown below:
I hope this helps
If you need to stay this column empty you can try to replace to ' '(blank). This will work if you column is not "Key"
Or try to use:
substitute a value when a null value is encountered
NVL( string1, replace_with )
You can do this using stored procedure. Below is the script for Create stored procedure.
CREATE PROCEDURE [dbo].[InsertIntoPicture]
#Album varchar(500)=null,
#id int=0 output
AS
BEGIN
insert INTO Picture(Album)VALUES(#Album)
SET #id=##IDENTITY
END
Below is the code for call stored procedure with C# .
string insertCmd = "InsertIntoPicture";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
Using above code you can insert a date from TextBox and also get last inserted record ID as an output variable as per your requirement.
Thanks .

Stored Procedure doesn't return records when called from C#, but works in SSMS

I have a stored procedure that correctly returns records when I call it from a SSMS query.
Here is the stored procedure:
CREATE PROCEDURE [dbo].[q_CheckRecords]
#ItemIDS AS VARCHAR(40)
AS
BEGIN
SET NOCOUNT ON
SELECT *
FROM q_Warehouse80_OOS_ItemsNeedingNotification
WHERE item_id = #ItemIDS
END
Calling this from a SSMS query like this:
exec [q_CheckOOSWarehouse80ItemsNeedingNotification] 'B30-R10000-B001'
It correctly returns a row, however when I use this C# code to call the stored procedure, I never get any rows returned.
SqlCommand cmd = null;
SqlDataReader myReader = null;
System.Data.SqlClient.SqlConnection conn = null;
conn = new System.Data.SqlClient.SqlConnection("Data Source=" + sSessionServer + ";database=" + sSessionDatabase + "; Integrated Security=SSPI");
String SQL = "[q_CheckOOSWarehouse80ItemsNeedingNotification]";
cmd = new SqlCommand();
cmd.CommandText = SQL;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.Parameters.Add("#ItemIDS", SqlDbType.VarChar).Value = ItemsToBeChecked;
conn.Open();
myReader = cmd.ExecuteReader();
// check to see if any rows were returned.
if (myReader.HasRows)
{
while (myReader.Read())
{
// code to read fields in returned rows here
}
}
conn.Close();
It appears to be a problem with how C# defines the datatype being passed to the stored procedure, but I haven't found any information online on how to solve this problem.
If I were to changed the stored procedure so it's "hard coded"
#ItemIDS AS VARCHAR(40)
AS
BEGIN
SET NOCOUNT ON
select * from q_Warehouse80_OOS_ItemsNeedingNotification where item_id = 'B30-R10000-B001'
END
then the C# call to it correctly indicates that a row was "found".
Any help would be greatly appreciated.
When you don't specify the length of a varChar sql treats it as length 1.
cmd.Parameters.Add("#ItemIDS", SqlDbType.VarChar).Value = ItemsToBeChecked;
Your variable ItemsToBeChecked will be truncated, and I suspect there is nothing matching in your database with just the first character of that value.
Specify the length of the varchar
cmd.Parameters.Add("#ItemIDS", SqlDbType.VarChar, 40).Value = ItemsToBeChecked;
You can verify this is the case by putting a profiler on sql, and executing your c#. You will see the value passed to the #ItemIDS parameter is only 1 character long.
The issue you are facing is because you are not calling your stored procedure in your C# Code.

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";

problem with my C# code in inserting in mysql

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;

Categories