Update statement in MySQL using C# - c#

I've been building a small inventory system for my workplace and have stumbled on an error that I cannot seem to fix
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
I have no idea what to change here.
Any help would be appreciated.

Problem: You are missing the comma after location parameter in your query.
Solution: You need to separate the parameters using a comma.
Suggestion : Use parameterized queries to avoid SQL Injection Attacks.
Try this:
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber=#Inventorynumber,Inventory_Name=#Inventory_Name, Quantity =#Quantity ,Location =#Location,Category =#Category WHERE Inventorynumber =#Inventorynumber";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#Inventory_Name",name);
cmd.Parameters.AddWithValue("#Quantity",quant);
cmd.Parameters.AddWithValue("#Location",location);
cmd.Parameters.AddWithValue("#Category",category);
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(numquery));
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}

Yes the error is in the missing comma, but this is the result of all that mess with string concatenation that ends always in subtle syntax errors.
Why don't you use a parameterized query? It is a lot simpler to write and you avoid parsing errors like this and (more important) you avoid Sql Injections
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
string query = "UPDATE Inventory SET Inventorynumber=#num, Inventory_Name=#name, " +
"Quantity =#qty,Location =#loc, Category =#cat " +
"WHERE Inventorynumber =#numquery";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, serverconnection);
cmd.Parameters.AddWithValue("#num", Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#qty", quant);
cmd.Parameters.AddWithValue("#loc", location);
cmd.Parameters.AddWithValue("#cat", category);
cmd.Parameters.AddWithValue("#numquery", Convert.ToInt16(numquery));
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
As a side note I have some doubts about some parameters type. Are you sure that quantity is really a string as implied by the presence of quotes around your original value?
Also the numquery and num variables are of type string, you try to convert then to short integer and then you put them inside quotes (meaning that in the database the fields are of type text). This makes no sense at all. If the database expects numbers then do not use quotes, if the database expects strings then do not try to convert. Another reason to use a parameterized query that force you to reflect on these issues.

You are missing a Comma between location and category. You have heard this million times befor i know, but its really much better using prepared statements so you do not have to take care of this kind of things and your code is much more readable.

You missed the comma
Location ='" + location + "', Category ='" + category + "'
// see the `,` between Location and Category

you have missed comma(,) in query:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
Make it as:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "', Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";

Try removing the ' single quotes around the integers?

Related

Database to declared variable

I do want to pass StudName contents to my declared variable. i tried " +a.ToString+" But still i got errors
string a;
connection.Close();
connection.Open();
String strSQL = "select *from Students where StudName = '" +a.ToString() + "' and StudNum = '" + studentNumber;
OleDbCommand command = new OleDbCommand(strSQL);
StudNum = '" + studentNumber
The Database column for studentNumber is numeric but you're half treating it as alphanumeric.
Solution
StudNum = " + studentNumber
You need to use Parameterised commands to protect against an SQL Injection attack. This will also solve issues such as variables containing apostrophes and etc that would also cause your sql to fail.

Use * as a wildcard when filtering data

I am looking to perform a search on multiple columns from an access database in C#.
The data is built in rows with each column either holding relevant data or "*" as a wildcard.
So as a rough example:
If i had data that was (, indicates new cell)
Ford, Fiesta, *, 1998
then if i had a value...
Ford, Fiesta, Petrol, 1998
it would find and display the row of data.
Currently I am trying:
string sql = "SELECT * FROM [mydatabase]
WHERE Manufacturer ='" + textBox1.Text +
"' OR Manufacturer='*' AND Model ='" + textBox2.Text +
"' OR Model='*' AND Fuel ='" + textBox3.Text +
"' OR Fuel='*' AND Year='" + textBox4.Text + "' OR Year='*'";
But this is bringing up all values rather than filtering them down. Is there a way of using and if/else within the query instead of OR?
If you want to use a wild card, I would just exclude it from the where clauses.
Alternateively, if you want to search all columns as one string you could add them all to a new column in the select list.
for example:
public void GetCars(string manufacturer, string model, string fuel, DateTime? year, string searchString)
{
string query = #"
SELECT *,
ISNULL([Manufacturer],'') + ' ' + ISNULL([Model],'') + ' ' ISNULL([Fuel],'') + ' ' ISNULL('Year', '') AS [SearchString]
FROM [MyDatabase]
WHERE [Manufacturer]=#Manufacturer ";
if (!String.IsNullOrEmpty(model))
query += #"AND [Model]=#Model ";
if (!String.IsNullOrEmpty(fuel))
query += "AND [Fuel]=#Fuel ";
if (year.HasValue)
query += "AND [Year]=#Year ";
if (!String.IsNullOrEmpty(searchString))
query += #"AND [SearchString] Like '%#SearchString%' ";
using (SqlCommand sqlCommand = new SqlCommand(query))
{
sqlCommand.Parameters.AddWithValue("#Manufacturer", manufacturer);
if (!String.IsNullOrEmpty(model))
sqlCommand.Parameters.AddWithValue("#Model", model);
if (!String.IsNullOrEmpty(fuel))
sqlCommand.Parameters.AddWithValue("#Fuel", fuel);
if (year.HasValue)
sqlCommand.Parameters.AddWithValue("#Year", year.Value);
if (!String.IsNullOrEmpty(searchString))
sqlCommand.Parameters.AddWithValue("#SearchString", searchString);
//Execute to data table etc
}
}
Instead of Manufacturer ='" + textBox1.Text + "' OR Manufacturer='*', you can use coalesce, which is sort of an if/else:
string sql = "... Manufacturer = coalesce('" + textBox1.Text + "', '*') ...";
In that way, you only need ands, and not mixed with or. This is probably giving the problem now, since the ors cause the and not to be evaluated.
You can also add parenthesis around the and, so the or will be applied only inside the parenthesis:
string sql = "... where (Manufacturer ='" + textBox1.Text + "' OR Manufacturer='*') and ...";
Note you should use parameterized queries, so you would get something like this:
command.CommandText = "select * from ... where Manufacturer = coalesce(#mgr, '*') and ...";
command.Parameters.Add(new SqlParameter("mgr", textBox1.Text));

No value given to one or more parameters

So I input some data into textbox then I click this button
private void button2_Click(object sender, EventArgs e)
{
command.Connection = connect;
if (idkaryawantxt.Text != "")
{
string q = "UPDATE tableAbsensi SET Absen_keluar =('" + (DateTime.Now.ToString("hh:mm")) + "') WHERE ID ='" + idkaryawantxt.Text.ToString() + "' AND Tanggal ='" + (DateTime.Now.ToString("MM-dd-yyyy")) +"'";
dosomething(q);
}
this.Close();
}
Then it says
No value given to one or more parameters
The table looked like this :
Check not only if idkaryawantxt is empty but also if it is not null:
if (string.IsNullOrEmpty(idkaryawantxt.Text))
{
var currentDateTime = DateTime.Now;
string q = "UPDATE tableAbsensi SET Absen_keluar ='"
+ currentDateTime.ToString("hh:mm") + "' WHERE ID ='"
+ idkaryawantxt.Text + "' AND Tanggal ='"
+ currentDateTime.ToString("MM-dd-yyyy") +"'";
dosomething(q);
}
Secondly the brackets here (DateTime.Now.ToString("hh:mm"))and here (DateTime.Now.ToString("MM-dd-yyyy")) are not needed.
You do not need to convert idkaryawantxt.Text to string (idkaryawantxt.Text.ToString()), as it is already a string.
You do not need brackets here SET Absen_keluar =('"and here "') WHERE ID ='" .
What is more it might be useful to set the DateTime.Now to a variable instead of calling it twice, because in some exceptional cases it could give you two different values.
And finally: avoid creating your queries in the way you did in this case. It is not an elegant way of creating queries + it is not secured against SQL injections.

Insert Date into sql table with Date column

Hello and thanks for reading.
I'm trying to insert the current date into my table, but I can't figure out how to write it correctly.
Here is my C# code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
conn.Open();
string Comment = UserWriteComment.Text;
string ID = DetailedID.Text;
string Name = DetailedName.Text;
string UniqueID = lblID.Text;
string query = "INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)" + "Values('" + ID + "', '" + Name + "', '" + Comment + "', '" + UniqueID + "', '" + Date + "')";
using (SqlCommand com = new SqlCommand(query, conn))
{
com.ExecuteNonQuery();
UserWriteComment.Text = "";
}
In the Query, There is a value called Date. This is here I like the Function to pass the current date into my Table.
I hope you can help me because I didnt managed to find the answer anywere.
Thanks:)
Use DateTime.Now or (in the database via sql) GetDate(). But more important, use sql-parameters to prevent sql-injection and conversion/localization issues:
string insertSql = #"INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)
Values(#ID, #Name, #Comment, #UniqueID, #Date)";
using (var conn = new SqlConnection("...."))
using (var com = new SqlCommand(insertSql, conn))
{
com.Parameters.AddWithValue("#ID", ID);
com.Parameters.AddWithValue("#Name", Name);
com.Parameters.AddWithValue("#Comment", Comment);
com.Parameters.AddWithValue("#UniqueID", UniqueID);
com.Parameters.AddWithValue("#Date", DateTime.Now);
conn.Open();
com.ExecuteNonQuery();
}
The using-statement ensures that unmanaged resources like the connection will be disposed/closed even in case of an error.
Use DateTime.Now instead of Date. i.e. update the INSERT line to the following.
string query = "INSERT INTO Comment(TicketID, Name, Comments, UserID, Date)"
+ "Values('" + ID + "', '" + Name + "', '" + Comment + "', '"
+ UniqueID + "', '" + DateTime.Now + "')";
P.S: You really should be using Parameterize statements to avoid a Bobby Tables situation.
To fix this, implement it as shown by #Tim in his answer:
Instead of Date, try using the following
DateTime.Now
Another function that can help you is
GETDATE()
Date inserts for SQL Server is best used via :
GetDate()
or
Convert(Varchar, GetDate(), 101)
Note: converting the GetDate() value to varchar type 101 shortens the value to just the date w/o time stamp.

Error converting data type varchar to numeric. 1-17-2014

I am having a problem inserting a record, the error says, "Error converting data type varchar to numeric."
This is my set of codes:
private void btnSearchCustomer_Click(object sender, EventArgs e)
{
//Get Customer Records
DataSet dsCustomer = new DataSet();
dsCustomer = GetRecords("Customers");
frmBasicSearch newSearch = new frmBasicSearch();
newSearch.myDataSet = dsCustomer;
newSearch.ShowDialog();
int myRowPosition = newSearch.myRowPosition;
if (myRowPosition != -1) //will display the value inside the textboxes
{
//concuntinated values
this.txtCustomerNo.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerNo"].ToString();
this.txtCustomerName.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerName"].ToString();
this.txtCustomerAddress.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerAddress"].ToString();
groupProduct(true); //this will activate the buttons from the Product Section
}
cn.Close();
cn.Open();
SqlCommand cmdInsert = new SqlCommand();
cmdInsert.Connection = cn;
cmdInsert.Transaction = trnOrder;
cmdInsert.CommandType = CommandType.Text;
cmdInsert.CommandText =
"INSERT INTO ShoppingCart " +
"(OrderDate, CustomerNo, CustomerName, CustomerAddress, PurchaseOrderNo, AgentNo, AgentName, InvoiceNo, TotalAmount, OrderStatus) " +
"VALUES ('" +
dtpOrderDate.Value.Date.ToString() + "', '" +
txtCustomerNo.Text + "', '" +
txtCustomerName.Text + "', '" +
txtCustomerAddress.Text + "', '" +
txtPONo.Text + "', '0', 'Agent', '" +
txtInvoiceNo.Text + "', '" +
lblTotal.Text + "', 'Void'); " +
"SELECT TOP 1 ShoppingCartNo FROM ShoppingCart " +
"ORDER BY ShoppingCartNo DESC;";
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
txtOrderNo.Text = nShoppingCart.ToString();
cmdInsert.ExecuteNonQuery();
cn.Close();
}
the highlighted part is the
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
I cannot seem to know where is the problem? thank you for your help.
I think you have taken "CustomerNo" field in database numeric field and you are trying to insert varchar or string value in that field as i am able to see your code in which you are putting "txtCustomerNo.Text" which will contain string value. You should convert your value fisrt in int or whatever you have taken your database field.
Hopefully this will be helpful for you.
Can you run the script without the Convert method. Replace it with:
string nShoppingCart = cmdInsert.ExecuteScalar().ToString();
Then see what nShoppingCart value is, and see if that would ever convert to an integer.
Try adding following part
Convert.ToInt16(lblTotal.Text)

Categories

Resources