StoredProcedure with Mono c#? - c#

Can I use MySql Stored Procedure for my Mono C# Gtk+ app for Ubuntu?
I have try with..
using MySql.Data.MySqlClient;
// Prepare connecting to the database.
myConn = new MySqlConnection("server=localhost;database=table;uid=root;password=1234;");
cmd = myConn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = #"Call newRow()";
myConn.Open();
cmd.ExecuteNonQuery();
myConn.Close();
If I just make and hardcode sql string in my program, it work!
Like..
cmd.CommandText = #"insert into table ...
The problem is with the:
cmd.CommandType = CommandType.StoredProcedure
-Line.

If you get an error with the Open call, your connection string is wrong. That has nothing to do with your command.
That said, I think your command should only contain the stored procedures name. Just "newRow" without any additional database syntax like call or empty brackets.

Ok so.. Just remove the..
cmd.CommandType = CommandType.StoredProcedure
The MySql.Data.MySqlClient do not need this option to do Stored Procedure :)

Related

C# ADO.NET - Could Not Find Stored Procedure

I am trying to execute a stored procedure through C#, ADO.NET and below is the code I am trying to execute:
using (SqlConnection conn = new SqlConnection(".;Initial Catalog=MyDB;User ID=sa;Password=***"))
{
try
{
string cmdText = "dbo.sp_Create_FlaggedItemEntry #URI, #ID";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText = cmdText;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#URI", value1);
cmd.Parameters.AddWithValue("#ID", value2);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Now when I try to debug it, I got an error at the line - cmd.ExecuteNonQuery(); - "Could Not Find Stored Procedure dbo.sp_Create_FlaggedItemEntry"
I verified that the Connection String is all correct and Stored Procedure exists.
Further, If I change the line - cmd.CommandType = CommandType.StoredProcedure; to cmd.CommandType = CommandType.Text; it get executed successfully and as expected.
Can someone suggest what I am missing and doing wrong here - Please pardon me if it is something very basic as it is quite long since I last worked with ADO.NET
CommandType.StoredProcedure means that the CommandText should only contain the name of the stored procedure.
Remove the parameter names from the string.
Take the parameters out of the command text. Also, you don't need to specify dbo.
The reason it's working with CommandType.Text is because it's a legitimate SQL command like that - if you were to open up SSMS and type that in it'd work as long as you also create the variables #URI and #ID
Documentation here
You should mention Data Source / Server in connectionString. Also for CommandText #Slaks is correct.

c# register form mysql insert

So im having problem gettin some data in to the database.. Im really stuck, im quite new to c# and have not learned all keywords yet, im not getting any errors just some nothing adds to my database.
textBox2.Text = myPWD;
MySqlConnection conn = new MySqlConnection("test")
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES ('values = #val')";
MySqlCommand data = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
SelectCommand.Parameters.AddWithValue("#val", this.textBox2.Text);
conn.Closed()
Manipulate the concatenation of value in passing of parameters. Don't do it inside sql statement.
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES (#val)";
// other codes
SelectCommand.Parameters.AddWithValue("#val", "values = " + this.textBox2.Text);
the reason why the parameter is not working is because it was surrounded by single quotes. Parameters are identifiers and not string literals.
The next problem is you did not call ExecuteNonQuery() which will execute the command.
Before closing the connection, call ExecuteNonQuery()
// other codes
data.ExecuteNonQuery();
conn.Close();
You should Google around and you will receive lots of content
You need to run ExecuteNonQuery
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('11','seed');", con);
cmd.ExecuteNonQuery();
cmd.Close();

Unable to insert data to database in asp.net C#

I'm new in C# programming, so I'll appreciate if anyone can help me. I know there are similar question but I still can't find the solution for my problem. I'm developing a mock system, where when user bought the product, the system will store all the transaction details. the problem is, I cannot insert the data into the database. Here's the code:
using (SqlConnection conn = new SqlConnection
(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
string QueryA = "#Insert into TransDetails(AccountNumber,Amount,Provider"
+ ",Mobile Number,TransNum,TransDate, Status) "
+ " Values (#AccountNumber,#Amount,#Provider,#Mobile Number,"
+ "#TransNum,#TransDate,#Status";
using (SqlCommand cmd = new SqlCommand("InsertRecord", conn))
{
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = QueryA;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
}
and the stores procedures are as follows:
ALTER PROCEDURE InsertRecord1
#AccountNumber int,
#Amount nchar(10),
#Provider nchar(10),
#MobileNumber int,
#TransNum nchar(10),
#TransDate date,
#Status nchar(10)
AS
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,TransNum,TransDate,Status)
Values (#AccountNumber,#Amount,#Provider,#MobileNumber,#TransNum,#TransDate,#Status)
return
Really appreciate any help.
P/S: i dont know why the beginning of the stored procedures started with "alter".
I may be reading it wrong, but it looks like your stored procedure is not used at all. Try commenting out "cmd.CommandText = QueryA;" and substitute "cmd.CommandText = "InsertRecord1";" and change CommandType to StoredProcedure.
QueryA, by the way, is missing a paren at the end. However, the whole thing is unnecessary since you have a stored procedure that does the same thing and it's almost always preferable to use a stored procedure rather than embedded DML.
You must escape Mobile Number while brackets
Insert into TransDetails(AccountNumber,Amount,Provider,[Mobile Number],...
and remove the space in your parameter
...,#MobileNumber,#TransNum,#TransDate,#Status
and change the paramname in your command parameter
cmd.Parameters.AddWithValue("#MobileNumber", lblNumber.Text);
but seeing your stored procedure, the column Mobile Number has no space between it. Is it a typo error in your query on QueryA? If it is, then remove the space on it (also on parameter name)
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,...
or
change your CommandType.Text to CommandType.StoredProcedure and remove this line,
cmd.CommandText = QueryA;
You're using the wrong overload of the SqlCommand constructor. According to MSDN:
new SqlCommand(string, SqlConnection) Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection.
What you need to do is either set your CommandType for the sql command to CommandType.StoredProcedure and not use QueryA, or initialize the sql command with QueryA and not make use of your stored procedure.
As you can see there is # at the start of your SQL Statement.
Also you are not really using the Store Procedure.
You can Try this:
using (SqlConnection conn = new SqlConnection (ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("InsertRecord1", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
Tho I don't use SQL Commands, Adapters...etc. to access the data from the SQL Database. I prefer Microsoft Data Access ApplicationBlocks which is easy-to-use library provided by Microsoft to access data from SQL Server.
Download
You can download it here http://download.microsoft.com/download/VisualStudioNET/daabref/RTM/NT5/EN-US/DataAccessApplicationBlock.msi
Introduction
https://web.archive.org/web/20210304123854/https://www.4guysfromrolla.com/articles/062503-1.aspx

Clear a database table

I'm using the following code to clear a database table:
public void ClearAll()
{
SqlCommand info = new SqlCommand();
info.Connection = con;
info.CommandType = CommandType.Text;
info.CommandText = "edit_.Clear()";
}
Why does it not work?
With a sql command you usually pass a TSQL statement to execute. Try something more like,
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["con"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "DELETE FROM Edit_ ";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
You need to execute the command, so info.Execute() or info.ExecuteNonQuery().
Try info.CommandText='DELETE FROM edit_';
The CommandText attribute is the TSQL statement(s) that are run.
You also need a info.ExecuteNonQuery();
1) Decide whether to use a TRUNCATE or a DELETE statement
Use TRUNCATE to reset the table with all its records and indexes:
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "TRUNCATE TABLE [dbo].[Edit_]";
command.ExecuteNonQuery();
}
Use DELETE to delete all records but do not reset identity/auto increment columns
using (SqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = "DELETE FROM [dbo].[Edit_]";
command.ExecuteNonQuery();
}
Note that there is another line in the samples. In the sample you provided the SQL statement never gets executed until you call one of the ExecuteXXX() methods like ExecuteNonQuery().
2) Make sure you use the correct object (are you sure its called edit_?). I recommend to put the schema before the table name as in the examples before.
3) Make sure you use the correct connection string. Maybe everything worked fine on the production environment ;-)

Run stored procedure in C#, pass parameters and capture the output result

This is a simple task that I want to acheive but ASP.NET makes it quite difficult, next to impossible. I followed this question
Running a Stored Procedure in C# Button but found out ExecuteNonQuery does not return the output from query.
I tried this other approach but can't seem to pass the paremeters in this way
SqlConnection myConnection = new SqlConnection(myconnectionString);
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "usp_GetCustomer";
myCommand.SelectParameter <-- does not exist
Can someone write this simple code, how can I implement it? Basically I am passing a #username and #month (both character strings) to stored procedure and it returns a number that I want to capture and assign to a label control.
Thank you
The output from my query is this. It runs a complex query, create a temp table and then it runs
select ##rowcount
and I am capturing that.
Don't use SqlCommand.ExecuteNonQuery() if you actually want data from a result set.
Make sure your procedure uses set nocount on
Then use SqlCommand.ExecuteScalar()
return (int)myCommand.ExecuteScalar(); // value of select ##rowcount
Edit: As for your parameters:
myCommand.Parameters.AddWithValue("#username","jsmith");
myCommand.Parameters.AddWithValue("#month","January");
I prefer using linq-to-sql to handle stored procedures. Create a linq-to-sql model, where you add the SP you want to call. This will expose the SP as a function on the generated data context, where the parameters are ordinary C# functions. The returned values will be exposed as a collection of C# objects.
If you have multiple results from the SP things get a bit more complicated, but still quite straight forward.
Use the Parameters collection of the command to set the parameters, and the ExecuteScalar to run the query and get the value from the single-row single-column result.
Use using blocks to make sure that the connection and command are closed and disposed properly in any situation. Note that you have to provide the connection to the command object:
int result;
using (SqlConnection connection = new SqlConnection(myconnectionString)) {
using (SqlCommand command = new SqlCommand(connection)) {
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "usp_GetCustomer";
command.Parameters.Add("#username", SqlDbType.VarChar).Value = username;
command.Parameters.Add("#month", SqlDbType.VarChar).Value = month;
connection.Open();
result = (int)myCommand.ExecuteScalar();
}
}
using(SqlConnection myConnection = new SqlConnection(myconnectionString))
{
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "usp_GetCustomer";
myCommand.Parameters.Add("#USER_NAME", SqlDbType.VarChar).Value = sUserName; // user name that you pass to stored procedure
myCommand.Parameters.Add("#Month", SqlDbType.VarChar).Value = iMonth; // Month that you pass to stored procedure
// to get return value from stored procedure
myCommand.Parameters.Add("#ReturnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
myConnection .Open();
myCommand.ExecuteScalar();
// Returnvalue from stored procedure
return Convert.ToInt32(command.Parameters["#ReturnValue"].Value);
}
Simple code to get return value from SQL Server
SqlConnection myConnection = new SqlConnection(myconnectionString);
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "usp_GetCustomer";
myCommand.Parameters.Add("#USER_NAME", SqlDbType.VarChar).Value = sUserName; // user name that you pass to the stored procedure
myCommand.Parameters.Add("#Month", SqlDbType.VarChar).Value = iMonth; //Month that you pass to the stored procedure
// to get return value from the stored procedure
myCommand.Parameters.Add("#ReturnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
myConnection .Open();
myCommand.ExecuteScalar();
// Returnvalue from the stored procedure
int iReturnValue = Convert.ToInt32(command.Parameters["#ReturnValue"].Value);

Categories

Resources