Passing a stored procedure as a string - c#

How do I pass a stored procedure along with parameters as a string to a function?
I tried this code but no luck..
This is the Business Access Layer code
try
{
string Query_string = "SP_InsertOffer_Tab #offer_name ='" + this.offer_name +"', #offer_price = " + this.offer_price + ",#start_date = '" + this.start_date +
"',#end_date = '" + this.end_date + "'";
int result = DbAcess.Insert_Query(Query_string);
return result;
}
catch (Exception ex)
{
throw ex;
}
finally
{
DbAcess = null;
}
Database layer code is as follows
public int Insert_Query(string strSQL)
{
SqlConnection con = new SqlConnection();
con = OpenConnection();
try
{
sqlcmd = new SqlCommand();
sqlcmd.Connection = con;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = strSQL;
int Result = sqlcmd.ExecuteNonQuery();
return Result;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}

Instead of passing strSQL as the CommandText, where strSQL is the string you create in the first code block (I think...), just pass the SP name as the CommandText and then add Parameters to your sqlcmd object.
SqlParameter p = new SqlParameter("#ParameterName", parametervalue));
sqlcmd.Parameters.Add(p);

Just to try to RESOLVE your problem, but BEWARE that this method is very dangerous and NOT RECOMMENDED for the Sql Injection problem.
string Query_string = "EXEC SP_InsertOffer_Tab #offer_name ='" +
this.offer_name +"', #offer_price = " +
this.offer_price + ",#start_date = '" +
this.start_date + "',#end_date = '" + this.end_date + "'";
and change the CommandType to Text.
A better approach would be to change the Insert_Query method
public int Insert_Query(string strSQL, SqlParameter[] prm)
{
using(SqlConnection con = OpenConnection())
{
sqlcmd = new SqlCommand(strSql, con);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddRange(prm)
int Result = sqlcmd.ExecuteNonQuery();
return Result;
}
}
then call it in this way
SqlParameter[] prms = new SqlParameter[]
{
new SqlParameter("#offer_name", SqlDbType.NVarChar),
new SqlParameter("#offer_price", SqlDbType.Money),
new SqlParameter("#start_date", SqlDbType.SmallDateTime),
new SqlParameter("#end_date", SqlDbType.SmallDateTime)
};
prms[0].Value = this.offer_name;
prms[1].Value = this.offer_price;
prms[2].Value = this.start_date;
prms[3].Value = this.end_date;
int result = DbAcess.Insert_Query(Query_string, prms);

Related

i get the error MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax

MySql.Data.MySqlClient.MySqlException: '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 'order' at line 1'"
my get and post methods in my web api are not working but all the other get methods for the other classes are working and they apply the same principle i get the error form above
my code is as follows:
public long saveOrder(Order o)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
String strsql = "INSERT INTO order (user_id_order,order_date,order_status,product_id_order,car_regplate,estimated_arrival,supplier_id_order,driver_id_order) VALUES(" + o.User_Id_Order + ",'" + o.Order_Date.ToString("yyyy-MM-dd HH:mm:ss") + "','" + o.Order_Status + "'," + o.Product_Id_Order + ",'" + o.Car_RegPlate + "','" + o.Estimated_Arrival.ToString("yyyy-MM-dd HH:mm:ss") + "'," + o.Supplier_Id_Order + "," + o.Driver_Id_Order + ")";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
command.ExecuteNonQuery();
long cId = command.LastInsertedId;
return cId;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve a user from the db using select statement
public Order getOrder(long id)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening connection
connection.ConnectionString = connString;
connection.Open();
Order o = new Order();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order WHERE order_id = " + id.ToString();
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
if (reader.Read())
{
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
return o;
}
else
{
return null;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve all users from the db using select statement
public ArrayList getOrders()
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
ArrayList oArraylist = new ArrayList();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order";
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
while (reader.Read())
{
Order o = new Order();
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
oArraylist.Add(o);
}
return oArraylist;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}

Record always does not exist in my code using C#

I have a part of code that I want to check if a value exists before I add it to my database. The result is always that my record does not exist and I don't why?
public bool IsClientExist(string valuetocheck)
{
bool result = false;
try
{
string strQuery = "SELECT * FROM [" + strFileNamenopath + "] WHERE client = '" + valuetocheck + "'";
OleDbCommand cmd = new OleDbCommand(strQuery, conn);
OleDbDataReader reader = cmd.ExecuteReader();
result = reader.Read();
if (reader.Read())
{
result = true;
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace.ToString() + " " + ex.Message);
}
return result;
}
EDIT : I get error after changing code by sqlparamers
public bool IsClientExist(string valuetocheck)
{
.....
SqlParameter param = new SqlParameter
{
ParameterName = "#client",
Value = valuetocheck,
};
cmd.Parameters.Add(param);
var data = cmd.ExecuteScalar();
result = (int)data > 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace.ToString() + " " + ex.Message);
}
return result;
}
ERROR:
"The OleDbParameterCollection only accepts non-null OleDbParameter type objects, not SqlParameter objects."
EDIT2 :
the problem is hapenning with one database (i try to create new one but same problem), i have other bases to check duplicat value and it's just work fine the code below is work with all databases except this.
public bool IsRecordExist(string valuetocheck)
{
bool result = false;
try
{
string strQuery = "SELECT * FROM [" + strFileNamenopath + "] WHERE code = '" + valuetocheck + "'";
OleDbCommand cmd = new OleDbCommand(strQuery, conn);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
result = true;
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Duplicate value " + ex.Message);
}
return result;
}
You should change your query to be a scalar one rather. As well parameterize your query to avoid SQL Injection attack
string strQuery = "SELECT count(*) FROM [" + strFileNamenopath + "] WHERE client = #client";
Use ExecuteScalar() then
OleDbCommand cmd = new OleDbCommand(strQuery, conn);
SqlParameter param = new SqlParameter
{
ParameterName = "#client",
Value = valuetocheck,
};
cmd.Parameters.Add(param);
var data = cmd.ExecuteScalar();
Set your flag accordingly
result = data > 0;
I found the answer !
the problem is in adding record to database, when i add 'accidentally' a space to the name , so rather to add data like AddData ("New Client") the code was like this AddData (" New Client") and whene comparing the inputs in database will be false "New Client" != " New Client"

Having SQL Syntax error in c#

I'm writing a script to add a bug report in the bug tracking system.
While after clicking the submit button, the SQL syntax error dialog have been pop-up.
Here is my coding
public partial class AddBugForm : Form
{
public AddBugForm()
{
InitializeComponent();
Fillcombo();
Fillcombo1();
Fillcombo2();
}
void Fillcombo()
{
string constring = "datasource = localhost; username = root; password = ";
string Query = "select * from bug.type";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string type = myReader.GetString("Type_of_bug");
comboBox1.Items.Add(type);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Fillcombo1()
{
string constring1 = "datasource = localhost; username = root; password = ";
string Query1 = "select * from bug.severity";
MySqlConnection conDataBase1 = new MySqlConnection(constring1);
MySqlCommand cmdDataBase1 = new MySqlCommand(Query1, conDataBase1);
MySqlDataReader myReader;
try
{
conDataBase1.Open();
myReader = cmdDataBase1.ExecuteReader();
while (myReader.Read())
{
string severity = myReader.GetString("severity");
severity_combo.Items.Add(severity);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Fillcombo2()
{
string constring2 = "datasource = localhost; username = root; password = ";
string Query2 = "select * from bug.priority";
MySqlConnection conDataBase2 = new MySqlConnection(constring2);
MySqlCommand cmdDataBase2 = new MySqlCommand(Query2, conDataBase2);
MySqlDataReader myReader;
try
{
conDataBase2.Open();
myReader = cmdDataBase2.ExecuteReader();
while (myReader.Read())
{
string priority = myReader.GetString("priority");
priority_combo.Items.Add(priority);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void submit_button_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;username=root;password=";
string Query = "INSERT INTO 'bug.bug' (Bug_ID, title, Type_of_bug, software, software_version, description, step_to_reproduction, severity, priority, symptom) values('" + this.bugid_txt.Text+"', '" + this.title_txt.Text + "','" + this.comboBox1.Text + "','" + this.software_txt.Text + "','" + this.software_version_txt.Text + "','" + this.description_txt.Text + "','" + this.step_to_reproduction_txt.Text + "','" + this.severity_combo.Text + "','" + this.priority_combo.Text + "','" + this.symptom_txt.Text + "');";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Saved");
while(myReader.Read())
{
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Please help me :((((
I see two issues with context of syntax error in your INSERT query
first, INSERT INTO 'bug.bug'; remove those single quotes else it's a literal value and not table name. It should be INSERT INTO bug.bug
Second, remove the semicolon from last of your query statement
.... + this.symptom_txt.Text + "');";
^.... this semicolon
replace this INSERT INTO 'bug.bug' by
INSERT INTO `bug.bug`
your table name is tarted as string and mysql engine doesn't see the table.
What is the syntax error you are getting?
Couple of points regarding the Insert statement.
You should not build the SQL command string by combining the value strings, this can create SQL injection problems and easily cause syntax errors. Instead you should use Parameters. Parameters also make the syntax a lot simpler.
You should use the ExecuteNonQuery command instead of a Reader, as the Insert statement is not reading any data
Updated statement (only two values used to make it smaller):
string Query = "INSERT INTO bug.bug (Bug_ID, title) values (#id, #title)"
MySqlConnection conDataBase = new MySqlConnection (constring);
MySqlCommand cmdDataBase = new MySqlCommand (Query, conDataBase);
cmdDataBase.Parameters.AddWithValue ("#id", bugid_txt.Text)
cmdDataBase.Parameters.AddWithValue ("#title", title_txt.Text)
conDataBase.Open();
cmdDataBase.ExecuteNonQuerty ();
MessageBox.Show("Saved");
Using Parameters will probably solve your syntax error.

SQL visual studio command

i am trying to update a mysql database through visual studio
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
string cmdstr="update npanxx set \""+col1+"\" = \""+newval1+"\" where NPA_NXX=\""+val1+"\"";
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
when I run this and click the button it says I have a syntax error but I have not be able to find it. Can anyone point it out to me
You don't need quotes around the column col1:
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
string cmdstr="update npanxx set "+col1+" = \""+newval1+"\" where NPA_NXX=\""+val1+"\"";
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
I would do it this way:
String str = "server=localhost;database=population;username=root;password=hello;Convert Zero Datetime=true;";
MySqlConnection con = new MySqlConnection(str);
string col1 = col.Text;
string newval1=newval.Text;
string val1=val.Text;
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand("Update npanxx set '"+ col1 +"'='" + newval1 + "' WHERE NPA_NXX= '" + val1 + "'", con);
MySqlCommand cmd = new MySqlCommand(cmdstr, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}

Updating multiple tables using SqlDataAdapter

I've been trawling through pages and pages on the internet for days now trying different approaches and I'm still not sure how I should be doing this.
On my third InsertCommand, I'd like to reference a column on the other 2 tables.
// Populate a DataSet from multiple Tables... Works fine
sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand("SELECT * FROM hardware", sqlConn);
sqlDA.Fill(ds, "Hardware");
sqlDA.SelectCommand.CommandText = "SELECT * FROM software";
sqlDA.Fill(ds, "Software");
sqlDA.SelectCommand.CommandText = "SELECT * FROM join_hardware_software";
sqlDA.Fill(ds, "HS Join");
// After DataSet has been changed, perform an Insert on relevant tables...
updatedDs = ds.GetChanges();
SqlCommand DAInsertCommand = new SqlCommand();
DAInsertCommand.CommandText = "INSERT INTO hardware (host, model, serial) VALUES (#host, #model, #serial)";
DAInsertCommand.Parameters.AddWithValue("#host", null).SourceColumn = "host";
DAInsertCommand.Parameters.AddWithValue("#model", null).SourceColumn = "model";
DAInsertCommand.Parameters.AddWithValue("#serial", null).SourceColumn = "serial";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Hardware"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO software (description) VALUES (#software)";
DAInsertCommand.Parameters.AddWithValue("#software", null).SourceColumn = "description";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Software"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO join_hardware_software (hardware_id, software_id) VALUES (#hardware_id, #software_id)";
// *****
DAInsertCommand.Parameters.AddWithValue("#hardware_id", null).SourceColumn = "?"; // I want to set this to be set to my 'hardware' table to the 'id' column.
DAInsertCommand.Parameters.AddWithValue("#software_id", null).SourceColumn = "?"; // I want to set this to be set to my 'software' table to the 'id' column.
// *****
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "HS Join");
Could somebody please tell me where I am going wrong and how I could potentially overcome this? Many thanks! :)
With regards to your comments this seems to be one of those occasions where if you and I were sat next to each other we'd get this sorted but it's a bit tricky.
This is code I've used when working with SqlConnection and SqlCommand. There might be stuff here that would help you.
public static void RunSqlCommandText(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
}
public static int RunSqlAndReturnId(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
int id = -1;
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
var returnvalue = comm.ExecuteScalar();
if (returnvalue != null) {
id = (int)returnvalue;
}
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
return id;
}

Categories

Resources