Error in mysql stored procedure with c# - c#

I want to use a stored procedure in mySql and it must return identity_scope(). I try this but don't work:
CREATE DEFINER=`root`#`localhost` PROCEDURE `InsertVideo`(
OUT out_scope_id INT,
IN in_youtubeidvideo VARCHAR(15),
IN in_title VARCHAR(200),
IN in_rating DOUBLE,
IN in_viewcount INT
)
BEGIN
INSERT INTO Video
(
YoutubeIdVideo,
Title,
Rating,
ViewCount,
DataAdded,
ConvertedFlag
)
VALUES
(
in_youtubeidvideo,
in_title,
in_rating,
in_viewcount,
CURDATE(),
false
);
END
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["AxWaveConnection"].ToString()))
{
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
MySqlCommand cmd = new MySqlCommand("InsertVideo", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("out_scope_id", scopeID);
cmd.Parameters.Add(new MySqlParameter("in_youtubeidvideo", VideoId));
cmd.Parameters.Add(new MySqlParameter("in_title", Title));
cmd.Parameters.Add(new MySqlParameter("in_viewcount", ViewCount));
cmd.Parameters.Add(new MySqlParameter("in_rating", Rating));
cmd.Parameters["out_scope_id"].Direction = ParameterDirection.Output;
try
{
cmd.ExecuteNonQuery();
scopeID = Convert.ToInt32(cmd.Parameters["out_scope_id"].Value);
}
catch (Exception)
{
scopeID = -1; //Duplicate Record
}
conn.Close();
}

You forgot to set the value of the parameter in your proc; the last line in your stored proc should read like this:
select out_scope_id = LAST_INSERT_ID();
BTW: SCOPE_IDENTITY() is a MS SQL Server function; not a MySQL function.

SELECT ##IDENTITY AS 'Identity';
GO

Related

Insert Select with Same Store Procedure

I am working on website with C#.I have Store Registration Details in two table that is login and registration.Data is inserted in table. Now when i am on login page this email_id and pasword is selected from Database.So, for that i have created one Store procedure which is`
ALTER PROCEDURE [dbo].[P_M_Login]
#Email_id nvarchar(50),
#Password nvarchar(50),
#Tran_Type nvarchar(1)
AS
BEGIN
SET NOCOUNT ON;
IF #Tran_Type='I'
if not exists(select 1 from M_Login where Email_id=#Email_id)
BEGIN
INSERT INTO M_Login ( Email_id, Password)
VALUES(#Email_id,#Password);
end
ELSE
IF #Tran_Type='S'
BEGIN
Select Email_id,Password from M_Login;
END
END`
Now i want to use this Store Procedure in my three tier architecture how can i pass tran type so it will be perfect for me.
This is my DAL Class coding for calling store procedure.
public Int32 Login(BALRegistration objBEL)
{
int result;
try
{
SqlCommand cmd1 = new SqlCommand("P_M_Login", con);
cmd1.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#Regisration_Id", objBEL.Registration_Id);
cmd1.Parameters.AddWithValue("#Email_id", objBEL.Email_id);
cmd1.Parameters.AddWithValue("#Password", objBEL.Password);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
result = cmd1.ExecuteNonQuery();
cmd1.Dispose();
if (result > 0)
{
return result;
}
else
{
return 0;
}
}
catch (Exception ex)
{
throw;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close();
}
}
}
}
}
Try this. Since you have parameter to be accepted in stored procedure, you just need to pass the parameter from the DAL
string type="s";
SqlCommand cmd1 = new SqlCommand("P_M_Login", con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#Email_id", objBEL.Email_id);
cmd1.Parameters.AddWithValue("#Password", objBEL.Password);
cmd1.Parameters.AddWithValue("#Tran_Type ", type);

Procedure has no parameters and arguments were supplied exception while my stored procedure accepts a parameter

below is the stored proc:
ALTER PROCEDURE Retrieve_Data
#noOfRecords INTEGER
AS
BEGIN TRY
SET NOCOUNT ON;
SELECT TOP(#noOfRecords) studentId
FROM Student;
END TRY
BEGIN CATCH
RETURN -101
END CATCH
RETURN 0
Below is the C# code:
DataSet ds = null;
try
{
using (SqlConnection conn = new SqlConnection(ConfigurationSettings.ConectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(storeProcName, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter param= new SqlParameter("#noOfRecords", SqlDbType.Int);
param.Value=10;
da.SelectCommand.Parameters.Add(param);
ds = new DataSet();
da.Fill(ds, "result");
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
return ds;
}
}
}
While executing the code I am getting a sql exception:
Procedure Retrieve_Data has no parameters and arguments were supplied
The syntax of your stored procedure is incorrect. You need to provide the input parameters inside brackets
ALTER PROCEDURE [dbo].[Retrieve_Data]
(
#noOfRecords INT
)
AS
BEGIN
Also you can try to clear your parameters inside the code:
if (conn.State == ConnectionState.Open)
{
da.SelectCommand.Parameters.Clear();;
conn.Close();
}
Change your stored procedure and wrap with BEGIN ... END
ALTER PROCEDURE [dbo].[Retrieve_Data]
#noOfRecords INT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
SELECT TOP(#noOfRecords) studentId
FROM Student;
END TRY
BEGIN CATCH
RETURN -101
END CATCH
RETURN 0;
END
Second thing about ordering table Student using ORDER BY ...

How to drop a table

I am using following C# method to execute SQL queries:
public bool ExecuteQuery(String pQuery)
{
SqlConnection con = new SqlConnection("MyConnectionString");
con.Open();
SqlTransaction trans = con.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
SqlCommand cmd = new SqlCommand(pQuery, con, trans);
cmd.ExecuteNonQuery();
trans.Commit();
con.Close();
trans.Dispose();
return true;
}
catch (Exception exp)
{
trans.Rollback();
con.Close();
MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
When I pass this statement:
ExecuteQuery("DROP TABLE MyTable");
then the method returns true, which means it worked fine, but when I check SQL Server, myTable was not dropped. If I run the same statement in SQL Server Management Studio, MyTable is dropped...
Where am I wrong?
Before answering your question, some comments:
Avoid coding such operations using query text, this is a high chance you can get problems with security. Better create stored procedure that executes table drop:
create procedure sp_DropTable
#tablename varchar(200)
as
BEGIN
DECLARE #SQL VARCHAR(MAX);
SET #SQL = 'IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N''' + #tableName + ''') AND type = (N''U'')) DROP TABLE [' + #tableName + ']'
EXEC (#SQL);
END
GO
Then pass the stored procedure's name as parameter to your function. Now back to your error.
Table drop is not a transaction, but you try to execute it in transactional schema. This makes it fail. Try:
public bool ExecuteQuery(String pQuery)
{
SqlConnection con = new SqlConnection("MyConnectionString");
con.Open();
try
{
SqlCommand cmd = new SqlCommand(pQuery, con);
// if you pass just query text
cmd.CommandType = CommandType.Text;
// if you pass stored procedure name
// cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
con.Close();
return true;
}
catch (Exception exp)
{
con.Close();
MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}

The stored procedure doesn't exist when calling SqlCommandBuilder.DeriveParameters

I'm tring to get the parameters from a stored procedure but I am getting the error of
The stored procedure 'Generic.proc_UpdateGenericCatalog' doesn't exist.
The namespace Generic. is causing the error but I do not know which setting I should use to get beyond this error.
--My Procedure--
ALTER proc [Generic].[proc_UpdateGenericCatalog]
#UserID UNIQUEIDENTIFIER,
#Name VARCHAR(30),
#SupplierName VARCHAR(30),
#SupplierEmail VARCHAR(50),
#SupplierPhone VARCHAR(12),
#GenericCatalogID INT
AS
UPDATE [Generic].[GenericCatalog]
SET [UserID] = #UserID
,[Name] = #Name
,[SupplierName] = #SupplierName
,[SupplierEmail] = #SupplierEmail
,[SupplierPhone] = #SupplierPhone
WHERE ID = #GenericCatalogID
--The C# code I'm using to get the parameter info--
--The error is right here SqlCommandBuilder.DeriveParameters(cmd);
How should I alter my code below so that I can get the .DeriveParameter info?
private static SqlParameter[] DiscoverParameters(string connectionString, string spName)
{
SqlCommand cmd = null;
SqlParameter[] discoveredParameters = null;
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = connectionString;
conn.Open();
cmd = new SqlCommand(spName, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(cmd);
conn.Close();
discoveredParameters = new SqlParameter[cmd.Parameters.Count];
cmd.Parameters.CopyTo(discoveredParameters, 0);
foreach (SqlParameter discoveredParameter in discoveredParameters)
{
discoveredParameter.Value = DBNull.Value;
}
cmd.Dispose();
}
}
catch (Exception) { throw; }
return discoveredParameters;
}
The most likely explanation is that the user specified in your connection string doesn't have permission to execute the Generic.proc_UpdateGenericCatalog procedure. I've just tested on one of my databases, and if the user doesn't have EXEC permission you'll get the "stored procedure doesn't exist" error.
Also, you should probably be cloning the parameters, rather than just copying them to an array. This is quite easy to do with a bit of LINQ:
private static SqlParameter[] DiscoverParameters(string connectionString, string spName)
{
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(spName, connection))
{
command.CommandType = CommandType.StoredProcedure;
connection.Open();
SqlCommandBuilder.DeriveParameters(command);
connection.Close();
return command.Parameters
.Cast<ICloneable>()
.Select(p => p.Clone())
.Cast<SqlParameter>()
.ToArray();
}
}

Exception returned when inserting into table through ASP.NET 3.5 C# method

I have a method that sends two variables, an int and a delimited string, to an SQL Server proc.
Variable values (copied from debugger):
detailId: 5
fileNames: "recruiter.txt|cert.pdf"
The method:
public void InsertFiles(int detailId, string fileNames)
{
ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings["PRADB"];
using (SqlConnection conn = new SqlConnection(connString.ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "dbo.InsertFiles";
cmd.Parameters.AddWithValue("#detailId", detailId);
cmd.Parameters.AddWithValue("#fileNames", fileNames);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string exc = ex.ToString();
}
finally
{
conn.Close();
}
}
}
Here is the proc:
ALTER PROCEDURE [dbo].[InsertFiles]
#detailId int,
#fileNames varchar(max)
AS
BEGIN
SET NOCOUNT ON;
insert into [dbo].[PRA_Files] (detailId, fileNames)
values (#detailId, #fileNames)
END
The exception received when debugging:
{"Incorrect syntax near 'dbo'."}
Yet when I execute from the proc:
exec [dbo].[InsertFiles] 5, "recruiter.txt|cert.pdf"
It works fine. There error isn't code side as it is being caught in the catch block of the method above. I'm stumped.
You need to specify that the command is a stored procedure:
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "dbo.InsertFiles";
cmd.Parameters.AddWithValue("#detailId", detailId);
cmd.Parameters.AddWithValue("#fileNames", fileNames);
cmd.CommandType = CommandType.StoredProcedure;

Categories