SQL dependency using stored procedure - c#

I am using SqlDependency in C# code to alert my application when there is a change in a particular column value in a row in database. I could achieve it using inline SQL.
I would like to replace it with stored procedure but for some reason the code isn't executing the stored procedure. I am pasting few lines of code from my application. Please let me know how to modify it so that I can have inline SQL replaced with a procedure call to achieve the same.
var con = new SqlConnection(ConnectionString);
SqlDependency.Stop(con.ConnectionString);
SqlDependency.Start(con.ConnectionString);
var connection = new SqlConnection(con.ConnectionString);
connection.Open();
try
{
using (var command = new SqlCommand("inlinesql", connection))
{
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
using (SqlDataReader rdr = command.ExecuteReader())
{
try
{
if (rdr.HasRows)
{
_autoEvent.WaitOne();
}
else
{
continue;
}
}
finally
{
rdr.Close();
}
}
}
}
finally
{
connection.Close();
SqlDependency.Stop(con.ConnectionString);
}
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
dosomething();
}

Above var dependency... put:
command.CommandType = CommandType.StoredProcedure;
And replace inlinesql with the name of the stored procedure.

Example code that worked for me:
using (var sqlConnection = new SqlConnection (_connectionString)) {
sqlConnection.Open ();
using (var sqlCommand = sqlConnection.CreateCommand ()) {
sqlCommand.Parameters.Clear ();
sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
// YOUR STORED PROCEDURE NAME AND PARAMETERS SHOULD COME HERE
sqlCommand.CommandText = "sp_InsertData";
sqlCommand.Parameters.AddWithValue ("#Code", e.Entity.Symbol);
sqlCommand.Parameters.AddWithValue ("#Name", e.Entity.Name);
sqlCommand.Parameters.AddWithValue ("#Price", e.Entity.Price);
try {
var sqlDataInsert = sqlCommand.ExecuteNonQuery ();
} catch (Exception ex) {
MessageBox.Show (ex.Message, this.Title);
}
}
}

Related

C# and MySql Procedure

I have 2 tables. Main_items and Help_items.
Main_items has these columns
(main_items_id,main_items_name)
Help_items has these columns
(help_items_id,Help_items_name, main_items_id).
I wrote this Procedure
CREATE DEFINER=`root`#`localhost` PROCEDURE `thamer1`(in main_items_id_ int,
out res int)
BEGIN
declare a int;
declare b int;
select count(help_items_id)
into a from help_items
where main_items_id=main_items_id_;
if a=0 then
set b=(main_items_id_*10)+1;
set res=b;
else
select COALESCE(max(help_items_id),0)+1
into res
from help_items
where main_items_id=main_items_id_;
end if;
END
This procedure works with MySql WrokBench.
And this for c# code
private void a_KeyDown(object sender, KeyEventArgs e)
{
using (MySqlConnection mysqlcon6 = new
MySqlConnection(connectString))
{
mysqlcon6.Open();
MySqlCommand mysqlcmd6 = new MySqlCommand("thamer1", mysqlcon6);
mysqlcmd6.CommandType = CommandType.StoredProcedure;
mysqlcmd6.CommandText = "thamer1";
mysqlcmd6.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = a.Text;
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32).Value=HITEM.Text;
mysqlcmd6.ExecuteNonQuery();
// MessageBox.Show("saved");
// GridFill();
}
}
I select value (for main_items_id) from DataGrideView and fetch it into textbox named a.
When I press ENTER I get this Message
System.FormatException:' Input string was not in a correct format'
I hope to help me to solve this error.
Remove the portion of this line that sets the parameter value:
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32).Value=HITEM.Text;
It looks like you expect that to bind the result of #res to the HITEM textbox, and that's not what happens. HITEM.Text is just a string, and when you assign that value to an int parameter, you're telling MySql you expect it to be able to parse that string into an int.
Instead, only create the parameter, like this:
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32);
You also need to tell ADO.Net this is an OUTPUT parameter. Then check the parameter value after the query runs by assigning the parameter value to HITEM.Text rather than from HITEM.Text:
private void a_KeyDown(object sender, KeyEventArgs e)
{
//You can re-use the *names* of these variables, since their scopes are limited to the method
//You can also stack them to share the same scope block and reduce nesting/indentation
using (var con = new MySqlConnection(connectString))
using (var cmd = new MySqlCommand("thamer1", con))
{
cmd.CommandType = CommandType.StoredProcedure;
// mysqlcmd6.CommandText = "thamer1"; //you already did this in constructor. Don't need to do it again
cmd.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = a.Text;
//DON'T assign to the Value, but DO make sure ADO.Net understands this is an OUTPUT parameter
cmd.Parameters.Add("#res", MySqlDbType.Int32).Direction = ParameterDirection.Output;
//wait as long as possible to call Open()
con.Open();
cmd.ExecuteNonQuery();
//Now you can assign **to** HITEM.Text, rather than from it.
HITEM.Text = cmd.Parameters["#res"].Value;
}
//End the scope as soon as possible, so the connection can be disposed faster
// MessageBox.Show("saved");
// GridFill();
}
And here it is again without all the extra comments:
private void a_KeyDown(object sender, KeyEventArgs e)
{
using (var con = new MySqlConnection(connectString))
using (var cmd = new MySqlCommand("thamer1", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = a.Text;
cmd.Parameters.Add("#res", MySqlDbType.Int32).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
HITEM.Text = cmd.Parameters["#res"].Value;
}
}
Even better practice would move all your SQL methods to a separate class, away from your event handlers. The event handlers should only need to call methods in the new class, like this:
public static class DB
{
private static string connectionString = "...";
public static int thamer(int main_item_id)
{
using (var con = new MySqlConnection(connectString))
using (var cmd = new MySqlCommand("thamer1", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = main_item_id;
cmd.Parameters.Add("#res", MySqlDbType.Int32).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
return (int)cmd.Parameters["#res"].Value;
}
}
}
private void a_KeyDown(object sender, KeyEventArgs e)
{
HITEM.Text = DB.thamer(int.Parse(a.Text)).ToString();
}
Change this
mysqlcmd6.Parameters.Add("#main_items_id_",
MySqlDbType.Int32).Value = a.Text;
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32).Value =
HITEM.Text;
to
int value1 = 0;
int value2 = 0;
if (!Int32.Text.TryParse(a.Text) || !Int32.TryParse(HITEM.Text))
{
return;
}
mysqlcmd6.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = value1;
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32).Value = value2;

Get Data from stored procedure as Datatable

I have a method to retrieve data from a database using a stored procedure as a DataTable like:
public DataTable GetTableBySQL(string sql)
{
SqlCommand cmd = new SqlCommand(sql.ToString(), this.dbconn)
{
CommandTimeout = 0,
CommandType = CommandType.Text
};
DataTable tbl = new DataTable("Table1")
{
Locale = System.Globalization.CultureInfo.InvariantCulture
};
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
da.SelectCommand.CommandTimeout = 0;
da.Fill(tbl);
}
catch (SqlException e)
{
this.HandleSQLError(e, "GetTableBySQL", sql.ToString());
}
finally
{
cmd.Dispose();
da.Dispose();
}
return tbl;
}
Now I call the stored procedure like this:
var empList = db.GetTableBySQL("$exec getMySP");
But when I execute, it just don't return any columns.
What am I doing wrong? Regards
There are three main problems here (other smaller ones, but three that are important):
The $exec part of the SQL doesn't mean anything. Maybe you just want exec.
When the bad SQL fails, the error is hidden from the program, so you don't really know what happened.
The method signature doesn't support query parameters, and therefore will force you to write horribly insecure code that will result in someone hacking your application. Probably sooner rather than later. This is really bad, and you should not ignore it.
Try something more like this:
public DataTable GetTableBySQL(string sql, params SqlParameter[] parameters)
{
var result = new DataTable();
//ADO.Net really does work better when you create a **NEW** connection
// object for most queries. Just share the connection string.
//Also: "using" blocks are a better way to make sure the connection is closed.
using (var dbconn = new SqlConnection(this.dbConnectionString))
using (var cmd = new SqlCommand(sql, dbconn))
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandTimeout = 0;
// A number of the properties set on the cmd and tbl variables just set the same value that was already there, didn't accomplish anything
//It's hard to understate how important it is to use parameterized queries.
if (parameters != null && parameters.Length > 0)
{
cmd.Parameters.AddRange(parameters);
}
try
{
da.Fill(result);
}
catch (SqlException e)
{
this.HandleSQLError(e, "GetTableBySQL", sql.ToString());
//you may want to re-throw here,
// or even just remove the try/catch and let the error bubble up to calling code
}
}
return result;
}
Here it is again without all the extra explanatory comments, so you can see that doing it right is less code, rather than more:
public DataTable GetTableBySQL(string sql, params SqlParameter[] parameters)
{
var result = new DataTable();
using (var dbconn = new SqlConnection(this.dbConnectionString))
using (var cmd = new SqlCommand(sql, dbconn))
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandTimeout = 0;
if (parameters != null && parameters.Length > 0)
{
cmd.Parameters.AddRange(parameters);
}
da.Fill(result);
}
return result;
}
Then call it like this:
var empList = db.GetTableBySQL("exec getMySP");

Combobox not filling from database C#

I'm trying to fill a combo box on from load from a database, I'm getting the error "Invalid object name 'POOL'"
Form load event to populate dropdown on form load
private void FRMAddTeam_Load(object sender, EventArgs e)
{
if (CMBBXPool.Items.Count > 0)
CMBBXPool.Items.Clear();
Database.CLSDB DatabaseClass = new Database.CLSDB();
DatabaseClass.FillDropDownList();
}
This is the code in my database connection class
public void FillDropDownList()
{
string PoolName = "";
Team.FRMAddTeam TeamAdd = new Team.FRMAddTeam();
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
Code to add the pool name
public void addPoolItem(string PoolName)
{
CMBBXPool.Items.Add(PoolName);
}
Any help is much appreciated
Your code needs to be:
public void FillDropDownList(Team.FRMAddTeam TeamAdd)
{
string PoolName = "";
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
You call it from your form like this:
DatabaseClass.FillDropDownList(this);
This will work, however it is strongly advised to change the implementation of your database class and remove tight coupling with GUI.
It is WRONG to fill your GUI from database class - instead of that, you should return data from your database class and bind your data to GUI in the GUI class.
http://en.wikipedia.org/wiki/Loose_coupling
http://en.wikipedia.org/wiki/Object_orgy
http://en.wikipedia.org/wiki/Separation_of_concerns
Sounds like you dont have table Pool.Are you sure its there?
Log into your SQL management studio and use query analyzer to run the same command.
There could be many reasons for that If your schema is different or do you have permission to access that table ? or are you checking the right database ?
UPDATE:
You should try using SELECT [Name] FROM dbo.TBL_Pool

Have trouble reading a null returned from stored procedure

I have a stored procedure that returns a single record, either null or data if present.
In my code I need to check what that procedure returns. What is the right way to do it?
Now when, running the code I have an exception saying: "Invalid attempt to read when no data is present." I'm using Visual Studio 2005.
Here is my method:
public static String GetRegionBasedOnIso(String isoNum)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);
String region = null;
try
{
using (SqlCommand cmd = new SqlCommand("MyProc", conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#isoNum", isoNum);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.IsDBNull(0))
{
return null;
}
else
{
region = (String)dr["region"];
}
}
}
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
finally
{
conn.Close();
}
return region;
}
What can I do to fix it? Thank you
if (dr.Read())
{
if (dr.IsDBNull(0))
{
return null;
}
else
{
region = (String)dr["region"];
}
}
else
{
// do something else as the result set is empty
}

ASP.NET SqlDataReader throwing error: Invalid attempt to call Read when reader is closed

This one has me stumped. Here are the relative bits of code:
public AgencyDetails(Guid AgencyId)
{
try
{
evgStoredProcedure Procedure = new evgStoredProcedure();
Hashtable commandParameters = new Hashtable();
commandParameters.Add("#AgencyId", AgencyId);
SqlDataReader AppReader = Procedure.ExecuteReaderProcedure("evg_getAgencyDetails", commandParameters);
commandParameters.Clear();
//The following line is where the error is thrown. Errormessage: Invalid attempt to call Read when reader is closed.
while (AppReader.Read())
{
AgencyName = AppReader.GetOrdinal("AgencyName").ToString();
AgencyAddress = AppReader.GetOrdinal("AgencyAddress").ToString();
AgencyCity = AppReader.GetOrdinal("AgencyCity").ToString();
AgencyState = AppReader.GetOrdinal("AgencyState").ToString();
AgencyZip = AppReader.GetOrdinal("AgencyZip").ToString();
AgencyPhone = AppReader.GetOrdinal("AgencyPhone").ToString();
AgencyFax = AppReader.GetOrdinal("AgencyFax").ToString();
}
AppReader.Close();
AppReader.Dispose();
}
catch (Exception ex)
{
throw new Exception("AgencyDetails Constructor: " + ex.Message.ToString());
}
}
And the implementation of ExecuteReaderProcedure:
public SqlDataReader ExecuteReaderProcedure(string ProcedureName, Hashtable Parameters)
{
SqlDataReader returnReader;
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
SqlCommand cmd = new SqlCommand(ProcedureName, conn);
SqlParameter param = new SqlParameter();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
foreach (DictionaryEntry keyValue in Parameters)
{
cmd.Parameters.AddWithValue(keyValue.Key.ToString(), keyValue.Value);
}
conn.Open();
returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (SqlException e)
{
throw new Exception(e.Message.ToString());
}
}
return returnReader;
}
The connection string is working as other stored procedures in the same class run fine. The only problem seems to be when returning SqlDataReaders from this method! They throw the error message in the title. Any ideas are greatly appreciated! Thanks in advance!
A DataReader is generally connected directly to the database. In this case, when you return from the method, you're returning from inside the using statement that created the SqlConnetion object. That will call Dispose on the SqlConnection, and render the SqlDataReader useless.
Try this:
public SqlDataReader ExecuteReaderProcedure(string ProcedureName, Hashtable Parameters)
{
SqlConnection conn = new SqlConnection(connectionString);
using(SqlCommand cmd = new SqlCommand(ProcedureName, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
foreach(DictionaryEntry keyValue in Parameters)
{
cmd.Parameters.AddWithValue(keyValue.Key.ToString(), keyValue.Value);
}
conn.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
Call it like this:
public AgencyDetails(Guid AgencyId)
{
evgStoredProcedure Procedure = new evgStoredProcedure();
Hashtable commandParameters = new Hashtable();
commandParameters.Add("#AgencyId", AgencyId);
using(SqlDataReader AppReader =
Procedure.ExecuteReaderProcedure("evg_getAgencyDetails",
commandParameters))
{
commandParameters.Clear();
while(AppReader.Read())
{
AgencyName = AppReader.GetOrdinal("AgencyName").ToString();
AgencyAddress = AppReader.GetOrdinal("AgencyAddress").ToString();
AgencyCity = AppReader.GetOrdinal("AgencyCity").ToString();
AgencyState = AppReader.GetOrdinal("AgencyState").ToString();
AgencyZip = AppReader.GetOrdinal("AgencyZip").ToString();
AgencyPhone = AppReader.GetOrdinal("AgencyPhone").ToString();
AgencyFax = AppReader.GetOrdinal("AgencyFax").ToString();
}
}
}
At the end of the using statement for AppReader, AppReader.Dispose will be called. Since you called ExecuteReader with CommandBehavior.CloseConnection, Disposing of the reader will also close the connection.
Note that I got rid of your bad exception handling as well. Never use ex.Message except possibly for displaying to end-users. Everyone else will want the full exception. Also, no need to print the method name as part of the exception message if you're allowing the full exception to propagate. The method name will be in the stack trace.

Categories

Resources