Deleting row in a table not workng - c#

I am trying to delete a row in my users_stocks table.
I use this code:
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM " + "users_stocks" + " WHERE user_name = '" + user_name + "'" + " AND " + "stock_symbol = " + "'" + stock_symbol + "'" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
There is a row with this data, but the query wont erase it.
What am i missing?

Use parametrized query to avoid Sql Injection Attacks and quoting problems
Not to mention that a parametrized query could be stored by the optimization engine of SqlServer and reused more quickly. An hand made query will be reevaluated every time you send to the database-
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM users_stocks " +
"WHERE user_name = #name AND stock_symbol = #stock" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
cmdnon.Parameters.AddWithValue("#name", user_name);
cmdnon.Parameters.AddWithValue("#stock", stock_symbol);
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}

As Luis Quijada mentioned above use parameters, they are much safer. In the code below just change the YOUR_CONNECTION_STRING value and the SqlDbType to the ones matching in your DB.
public bool removeStock(string user_name, string stock_symbol)
{
using(SqlConnection connection = new SqlConnection("YOUR_CONNECTION_STRING"))
{
using(SqlCommand command = new SqlCommand())
{
try
{
command.Connection = connection;
command.CommandText = "DELETE FROM user_stocks WHERE user_name=#USERNAME AND stock_symbol=#STOCKSYMBOL";
command.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_name.Trim();
command.Parameters.Add("#STOCKSYMBOL", SqlDbType.VarChar).Value = stock_symbol.Trim();
connection.Open();
int i = command.ExecuteNonQuery();
if (i == 0)
return false;
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
finally
{
connection.Close();
}
}
}
}

Try this code :
public bool removeStock(string user_name,string stock_symbol)
{
user_name = user_name.Trim();
stock_symbol = stock_symbol.Trim();
string statement = "DELETE FROM users_stocks
WHERE user_name = '" + user_name + "'
AND stock_symbol = '" + stock_symbol + "'" ;
SqlCommand cmdnon = new SqlCommand(statement, connection);
try
{
connection.Open();
int num = cmdnon.ExecuteNonQuery();
connection.Close();
return true;
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
connection.Close();
return false;
}
}
Change in query

Related

c# Invalid attempt to read when no data is present

I am unable to find the problem here but this does not work! Any help will be appreciated.
It is a bool thing BTW.Every time i debug, it logs an error as follows
Invalid attempt to read when no data is present
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
//myReader.Read();
if (myReader["name"].ToString() != "" ) /* ( myReader["name"].ToString() != "" */
{
myReader.Read();
value = true;
}
}
catch (Exception ex)
{
//ErrorLabel.Text = ex.Message;
hiba.Visible = true;
hiba.Text = ex.Message + "\n Check Insert Call User Device ÁLERT!";
}
myReader.Close();
conn.Close();
return (value);
}
#andrew, kindly go through below code and let me know is it working for you or not?
string connectionString = "[YOUR_CONNECTION_STRING]";
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
if (myReader.Read())
{
if (myReader["name"].ToString() != "")
{
value = true;
}
}
}
catch (Exception ex)
{
}
myReader.Close();
conn.Close();
return (value);
}

distinguish the columns of a stacked column chart

I want to draw a stacked chart from mysql database.
I want to have 4 columns named "port1", "port2", "port3" and "port4".
My problem is when I import the data from my DB, I check the type a column in the table then I draw the chart . My DB contains 4 types of port consequently I would have 4 columns named port1, port2, port3 and port4, but my code generate all the data but on the same column which is port1.
How can I add an identical number of datapoints?
try
{
con.Open();
string query1 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port1'" ;
string query4 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port4'";
SqlCommand cmmd = new SqlCommand(query1, con);
SqlCommand cmmd4 = new SqlCommand(query4, con);
SqlDataReader dataReader = cmmd.ExecuteReader();
while (dataReader.Read())
{
chart1.Series.Add(dataReader["name"].ToString());
chart1.Series[dataReader["name"].ToString()].ChartType = SeriesChartType.StackedColumn;
chart1.Series[dataReader["name"].ToString()]["StackedGroupName"] = "Group1";
chart1.Series[dataReader["name"].ToString()].Points.AddXY((dataReader["type"].ToString()), dataReader["value"].ToString());
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
try
{
con.Open();
string query1 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port1'" ;
SqlCommand cmmd = new SqlCommand(query1, con);
SqlDataReader dataReader = cmmd.ExecuteReader();
while (dataReader.Read())
{
chart1.Series.Add(dataReader["name"].ToString());
chart1.Series[dataReader["name"].ToString()].ChartType = SeriesChartType.StackedColumn;
chart1.Series[dataReader["name"].ToString()]["StackedGroupName"] = "Group1";
chart1.Series[dataReader["name"].ToString()].Points.AddXY((dataReader["type"].ToString()), dataReader["value"].ToString());
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
try
{
con.Open();
string query2 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port2'";
SqlCommand cmmd2 = new SqlCommand(query2, con);
SqlDataReader dataReader2 = cmmd2.ExecuteReader();
while (dataReader2.Read())
{
chart1.Series.Add(dataReader2["name"].ToString());
chart1.Series[dataReader2["name"].ToString()].ChartType = SeriesChartType.StackedColumn;
chart1.Series[dataReader2["name"].ToString()]["StackedGroupName"] = "Group2";
// MessageBox.Show(dataReader2["type"].ToString());
chart1.DataBind();
chart1.Series[dataReader2["name"].ToString()].Points.AddXY("Port_2", dataReader2["value"].ToString());
chart1.Series[dataReader2["name"].ToString()]["PointWidth"] = "1";
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error "+ ex);
}

Generic C# Function That Return Value From Database

The following function get parameters and return first value from sql server table. Its generic and very easy to use to get one value but it has security vulnerability of SQL Injection. May anyone help to alter the code to make it a parametric or any other way to secure for SQL Injection?
public static string getFieldValue(string tableName, string returnField, string whereCondition)
{
SqlConnection con = new SqlConnection(Utilities.ConnectionString());
SqlDataReader reader;
string returnValue;
try
{
string sql;
if (whereCondition != "")
sql = "SELECT " + returnField + " as ReturnField FROM " + tableName + " WHERE " + whereCondition;
else
sql = "SELECT " + returnField + " as ReturnField FROM " + tableName;
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
returnValue = reader["ReturnField"].ToString();
reader.Close();
return returnValue;
}
else
{
reader.Close();
return "";
}
}
catch (Exception err)
{
throw new ApplicationException(err.Message);
}
finally
{
con.Close();
con.Dispose();
}
}

update data using oledb in c#

I made a project using c# and data base using access accdb and connected between them both. I made 2 buttons, first one to add new costumer, which works perfectly, and second one to update the data of the costumer (first name and last name), for some reason, the update button does not work, there is no error when I run the project, but after I click nothing happens...
private void button2_Click(object sender, EventArgs e)
{
connect.Open();
string cid = textBox1.Text;
string cfname = textBox2.Text;
string clname = textBox3.Text;
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
if (connect.State == ConnectionState.Open)
{
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("ERROR");
}
}
I believe your commandtext is where the trouble lies;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
You require a comma between the set statements, and also as Gino pointed out the speechmarks.
Edit:
It's better than you use parameters for your variables, your current method is open to SQL injection, eg.
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand(#"UPDATE Tcostumers
SET cfname = #CFName,
clname = #CLName
WHERE cid = #CID", connect);
command.Parameters.AddWithValue("#CFName", textBox2.Text);
command.Parameters.AddWithValue("#CLName", textBox3.Text);
command.Parameters.AddWithValue("#CID", textBox1.Text);
try
{
connect.Open();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
finally
{
connect.Close();
}
}
Its how I tend to format my code, so do as you will with it. Hope it helps.
It might be a stupid thing but...
you're updating strings not ints so try adding '' to your strings something like:
command.CommandText = "UPDATE Tcostumers SET cfname= '" + cfname + "' clname='" + clname + "' WHERE cid = " + cid;
//my sample code for edit/update
Table Name = StudentFIle
Fields = id,fname,lname
bool found = false;
OleDbConnection BOMHConnection = new OleDbConnection(connect);
string sql = "SELECT * FROM StudentFIle";
BOMHConnection.Open();
OleDbCommand mrNoCommand = new OleDbCommand(sql, BOMHConnection);
OleDbDataReader mrNoReader = mrNoCommand.ExecuteReader();
while (mrNoReader.Read())
{
if (mrNoReader["id"].ToString().ToUpper().Trim() == idtextbox.Text.Trim())
{
mrNoReader.Close();
string query = "UPDATE StudentFIle set fname='" +firstnametextbox.Text+ "',lname='"+lastnametextbox.Text+"' where id="+idtextbox.Text+" ";
mrNoCommand.CommandText = query;
mrNoCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Updated");
found = true;
break;
}
continue;
}
if (found == false)
{
MessageBox.Show("Id Doesn't Exist !.. ");
mrNoReader.Close();
BOMHConnection.Close();
idtextbox.Focus();
}

Update Query problem in asp.net c# and Mysql using odbc

when i specify values in my update query the query works fine and the database gets updated, but when i use parameters in my query the database does not update
here is the code i have written
try
{
OdbcConnection MyConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
MyConnection.Open();
String MyString = "UPDATE orddetpabak SET jud1=#jud1,jud2=#jud2,jud3=#jud3,adv=#adv where fil_no=#fil_no AND orderdate=#orderdate";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
String j1=DropDownList4.SelectedValue;
String j2=DropDownList5.SelectedValue;
String j3=DropDownList6.SelectedValue;
String j4=TextBox4.Text;
String j5 = HiddenField1.Value;
String j6 = TextBox3.Text;
MyCmd.Parameters.AddWithValue("#jud1",j1);
MyCmd.Parameters.AddWithValue("#jud2",j2);
MyCmd.Parameters.AddWithValue("#jud3",j3);
MyCmd.Parameters.AddWithValue("#adv",j4);
MyCmd.Parameters.AddWithValue("#fil_no",j5);
MyCmd.Parameters.AddWithValue("#orderdate",j6);
Response.Write(DropDownList4.SelectedValue);
Response.Write(" " + DropDownList5.SelectedValue);
Response.Write(" " + DropDownList6.SelectedValue);
Response.Write(" " + TextBox4.Text);
Response.Write(" " + HiddenField1.Value);
Response.Write(" " + TextBox3.Text);
MyCmd.ExecuteNonQuery();
//MyConnection.Close();
}
catch(Exception epp)
{
Response.Write(epp);
}
Please Help
As far as I know you cannot use named parameters in MySQL. If you change your string to be
String MyString = "UPDATE orddetpabak SET jud1=?,jud2=?,jud3=?,adv=?
where fil_no=? AND orderdate=?";
and your parameters as:
MyCmd.Parameters.AddWithValue("",j1);
MyCmd.Parameters.AddWithValue("",j2);
MyCmd.Parameters.AddWithValue("",j3);
MyCmd.Parameters.AddWithValue("",j4);
MyCmd.Parameters.AddWithValue("",j5);
MyCmd.Parameters.AddWithValue("",j6);
Hope this helps.
It can be like the following: (I'm using the ADO.NET driver for MySQL version 6.3.7.0, latest one had some issues).
public bool UpdateCustomerIAR(IAR oIAR)
{
bool bRetVal = false;
try
{
MySqlConnection dbConnection = new MySqlConnection(APPSConn.ConnectionString);
MySqlCommand dbCommand = dbConnection.CreateCommand();
string szSQL = string.Empty;
szSQL = "UPDATE schema.table_name SET field_name_one=?field_name_one";
szSQL += " WHERE field_name_two=?field_name_two";
using (MySql.Data.MySqlClient.MySqlConnection conn = new
MySql.Data.MySqlClient.MySqlConnection(APPSConn.ConnectionString))
{
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = szSQL;
cmd.Parameters.AddWithValue("?field_name_one", oIAR.Title);
cmd.Parameters.AddWithValue("?field_name_two", oIAR.IARID.ToString());
conn.Open();
cmd.ExecuteNonQuery();
bRetVal = true;
}
return bRetVal;
}
catch (MySqlException ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
catch (Exception ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
}

Categories