SQLite with C# - UPDATE Command with Parameters - c#

I am creating a program where you can store and change the balances of different accounts in visual C#. At the moment I am making the part where you can add to the balance of an account stored in a database to a table like this:
After adding on an amount of money, thus changing the currency, I want to be able to change the currency value in the database.
For example, if the current currency of an account (record) is £2. After adding on £3 I want to change the database so in the currency field for that record it now says £5.
I have written this code which is similar to how I inserted information into the database earlier in the code which worked successfully but I can't figure out how to use the syntax for the update command whilst using parameters in this context (doesn't work):
string sql = "update customers set balance values ('" + balance + "') where first_name values ('" + forename + "')";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
(This is the code I used earlier to insert information into the table that works):
string sql = "insert into leaders (ID, username, password, first_name, last_name) values (null,'" + username + "', '" + password + "', '" + first_name + "', '" + last_name + "')";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

You aren't using the correct syntax for update:
string sql = "update customers set balance = '" + balance + "' where first_name = '" + forename + "'";
Note that this is not a parameterized query, and might be vulnerable to SQL Injection attacks (or just break if one of the values contains a '). It's recommended to use a prepared statement with parameters:
string sql = "update customers set balance = #balance where first_name = #forename";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("#balance", balance);
command.Parameters.AddWithValue("#forename", forename);
command.ExecuteNonQuery();

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.

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.

Update statement in MySQL using 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?

How can I add auto numbering in visual c# 2010? using ms Access?

I'm using autonumber but it doesn't work for me. I want auto numbering in my StudentID number.
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText =
"insert into Student(ID, Lastname, Middlename, Firstname, Address, DateofBirth, Birthplace, Contact_number, emailaddress, guardian_name, Guardian_contact) values ('" + txtStudentIDnumber.Text + "','" + txtlastname.Text + "','" + txtfirstname.Text + "','" +
txtmiddlename.Text + "','" + txtaddress.Text + "','" + txtdateofbirth.Text + "','" + txtbirthplace.Text + "','" + txtcontactnumber.Text + "','" + txtemailaddress.Text + "','" + txtGuardianname.Text + "','" + txtguardiancontact.Text + "')";
system.Connection = mydatabase;
if (MessageBox.Show("Save data?", "Confirm Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
It is difficult to determine the issue without the database schema or the error message. However, the issue is probably because you are trying to insert a value into the ID column when it may have auto numbering (also known as a counter) enabled. Change:
system.CommandText = "insert into Student(ID, Lastname, ..."; // And so on
to
system.CommandText = "insert into Student(Lastname, ..."; // And so on
Also consider changing the query to be a parameterized query (such as that mentioned in incorrect syntax near 's'. unclosed quotation mark after the character string ')') rather than using concatenation to avoid SQL injection and escaping issues.
first you should specify identity Column like this :
then your code :
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\db.accdb");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("insert into Student(LastName,...) values('{0}',...)",txtLastName.Text.Trim(),...);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Your ID column should be setup to be an identity (in the database), then you should omit it from the insert.
http://forums.asp.net/t/1492834.aspx/1
UPDATE
I suspect your StudentIdNumber is an actual stateissued ID number, and what you're looking for is an identity field.
You'll need to add an identity column to your table, either using the table designer you used to create the table, or using a script
CREATE TABLE Student(
ID int identity,
StudentIdNo varchar(10),
Lastname varchar(10),
Firstname varchar(10),
Middlename varchar(10),
CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID)
)
This will be the format of your insert statement, notice there is no ID field
"INSERT INTO Student (StudentIdNo, Lastname, Firstname, Middlename) VALUES (?)"
...in your case, after adding a identity field
OleDbCommand comm = new OleDbCommand();
comm.CommandType = CommandType.Text;
comm.CommandText =
#"insert into Student(StudentIdNo, Lastname, Firstname, Middlename)
values (#StudentIdNo, #Lastname, #Firstname, #Middlename)";
comm.Parameters.AddWithValue("#StudentIdNo", txtStudentIdNo.Text);
comm.Parameters.AddWithValue("#Lastname", txtlastname.Text);
comm.Parameters.AddWithValue("#Firstname", txtfirstname.Text);
comm.Parameters.AddWithValue("#Middlename", txtmiddlename.Text);
comm.Connection = mydatabase;

C# syntax error in INSERT INTO statement

I'm having the error at the line: ins.ExecuteNonQuery().ToString(); OledDbException was unhandled Syntax error in INSERT INTO statement.
How do I fix this?
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
string newTagID = textBox1.Text;
string newUser = textBox2.Text;
string newAge = textBox3.Text;
string newPhoneNumber = textBox4.Text;
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES ('" + newTagID + "', '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Connection.Open();
ins.ExecuteNonQuery().ToString();
ins.Connection.Close();
Your problem is probably one these three:
Outright syntax error not clearly visible with the hideous unparametrized SQL statement :p
newUser or some other field has a ' somewhere and is screwing up the syntax.
You are trying to insert a numeric value (Age?) as a string.
You should easily solve the first two creating a breakpoint after the insertString statement construction and checking out what the string really contains. The third one is even easier to check, just review the data types of the table's fields in your data base.
Notwithstanding, you should change the use of your command to use parameters and not build the query string with string concatenation (which is susceptible to sql injection attacks).
The issue is most likely because [Tag ID], User, Age, [Phone Number] are not all strings. In your SQL, any non-string column data should not be wrapped by quotes (').
To fix the immediate problem (assuming [Tag ID] is an integer):
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (" + newTagID + ", '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
However, you should structure your code to avoid sql injection, have cleaner code, and also not worry about the quotes:
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (#TagID, #User, #Age, #PhoneNumber)";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Parameters.Add(new OleDbParameter("#TagID",newTagID);
ins.Parameters.Add(new OleDbParameter("#User",newUser);
ins.Parameters.Add(new OleDbParameter("#Age",newAge);
ins.Parameters.Add(new OleDbParameter("#PhoneNumber",newPhoneNumber);
ins.Connection.Open();
ins.ExecuteNonQuery();
ins.Connection.Close();

Categories

Resources