I have a datagrid setup in my windows form in Visual Studio. The datagrid is updated from the textboxes but I can't get it to edit the values held in the database.
This is the code I am using:
private void btnUpdate_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=admin";
string Query = "UPDATE database.taxi SET PickupLocation='" + txtPickupLocation.Text + "',PickupArea='" + comboBxPickupArea.Text + "',PickupTime='" + dateTimePickup.Text + "',DestinationLocation'" + txtDestinationLocation.Text + "',DestinationArea='" + comboBxDestinationArea.Text + "',Name'" + txtCustomerName.Text + "',Address='" + txtCustomerAddress.Text + "',Tour='" + comboBxTour.Text + "',VehicleRegistration='" + txtvehicleregistration.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Entry has been updated");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
But I get the error:
"You have an error in your SQL syntax; check the manual that
corresponds to your SQL server version for the right syntax to use
near '"DestinationLocation'"......... "
Any help would be appreciated.
You forget to use = after your DestinationLocation and Name
Change your
DestinationLocation'" + txtDestinationLocation.Text
and
Name'" + txtCustomerName.Text + "'
to
DestinationLocation = '" + txtDestinationLocation.Text
and
Name = '" + txtCustomerName.Text + "'
But please don't use string concatenation in your sql queries. Use parameterized queries instead. This kind of string concatenations are open for SQL Injection attacks.
Also you don't need to use ExecuteReader since your query doesn't return anything. Use ExecuteNonQuery instead.
As a full code;
string Query = "UPDATE database.taxi SET PickupLocation=#PickupLocation, PickupArea=#PickupArea, PickupTime=#PickupTime, DestinationLocation=#DestinationLocation,
DestinationArea=#DestinationArea, Name=#Name, Address#Address, Tour=#Tour, VehicleRegistration=#VehicleRegistration";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
cmdDataBase.Parameters.AddWithValue("#PickupLocation", txtPickupLocation.Text);
cmdDataBase.Parameters.AddWithValue("#PickupArea", comboBxPickupArea.Text);
....
....
cmdDataBase.ExecuteNonQuery();
You need an equals sign after DestinationLocation in your SQL.
Incidentally, you probably don't want to use ExecuteReader, since you're not returning any values (and aren't interested in any.) Try ExecuteNonQuery.
ETA: and Soner Gönül is absolutely right about the need for parameterized queries rather than string concatenation!
Finally, I assume that you aren't going to hard-code your connection string in your final version?
Related
I was gonna save my date and time record in my database when an unhandled exception always thrown at this code: int value = cmd.ExecuteNonQuery(); when I'm clicking the 'Time In' button.
it says that MySql.Data.MySqlClient.MySqlException 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Mar 2022 3:53:00 AM,System.Windows.Forms.DateTimePicker, Value
When I check my codes, there's no errors. I debugged it but no errors appeared.
Here's my codes:
private void btnTimeIn_Click(object sender, EventArgs e)
{
string connectstring = "datasource=localhost;port=3306;username=root;password=;database=employeedb;SslMode=none";
MySqlConnection conn = new MySqlConnection(connectstring);
conn.Open();
string iQuery = "INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`, `RecordDate`, `TimeIn`, `TimeOut`) VALUES (" + txtEmployeeID.Text + "," + txtLstName.Text + "," + txtFirstName.Text + "," + dateTimePicker1.Value + "," + dateTimePicker2 + "," + dateTimePicker3 + ")";
MySqlCommand cmd = new MySqlCommand(iQuery, conn);
int value = cmd.ExecuteNonQuery();
MessageBox.Show(value.ToString());
conn.Close();
}
Your immediate help, tips and advice are highly appreciated
I was gonna expect that I'm gonna save records in my database by timing in... but I can't even find what could be wrong because i just did all ways of inserting data into table in database. Still, I didn't also work, and the exception still throwing every time at the 'cmd.ExecuteNonQuery' line.
This line of code is causing the bug, and can also lead to SQL injection:
string iQuery = "INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`, `RecordDate`, `TimeIn`, `TimeOut`) VALUES (" + txtEmployeeID.Text + "," + txtLstName.Text + "," + txtFirstName.Text + "," + dateTimePicker1.Value + "," + dateTimePicker2 + "," + dateTimePicker3 + ")";
You should always use command parameters, not string concatenation:
using (MySqlConnection conn = new MySqlConnection(connectstring))
{
conn.Open();
string iQuery = #"
INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`,
`RecordDate`, `TimeIn`, `TimeOut`)
VALUES (#id, #last, #first, #date, #in, #out);";
using MySqlCommand cmd = new MySqlCommand(iQuery, conn))
{
cmd.Parameters.AddWithValue("#id", txtEmployeeID.Text);
cmd.Parameters.AddWithValue("#first", txtLstName.Text);
cmd.Parameters.AddWithValue("#last", txtFirstName.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#in", dateTimePicker2.Value);
cmd.Parameters.AddWithValue("#out", dateTimePicker3.Value);
int value = cmd.ExecuteNonQuery();
}
}
Additionally, use using statements to automatically close and clean up database resources.
I have created a simple application every thing is working fine except update
portion insertion is working fine with same table data
My code is
private void button2_Click(object sender, EventArgs e)
{
string cmd = ("UPDATE submissionFee SET [stdName]='" + textBox2.Text + "', [fatherName]='" + textBox3.Text + "', [program]='" + textBox4.Text + "', [adress]='" + textBox5.Text + "',[email]='" + textBox6.Text + "', [cellNum]='" + textBox7.Text + "', [isPaid] = '" + textBox8.Text + "', [SubmissionDate] = '" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "'Where [ID]='" + textBox1.Text + "'");
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = cmd;
command.ExecuteNonQuery();
MessageBox.Show("Account Has Been Updated");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
MessageBox.Show("Please Enter Valid Data");
}
}
Error Screenshot
Probably the connection is already open when you try to open it.
Either:
1) Make sure you close the connection from the last time you used it.
2) Or, if it is sometimes supposed to be kept open, check if the connection is already open, and don't close it if it is. Something like:
bool bWasOpen = (connnection.State == ConnectionState.Open);
if (!bWasOpen)
connection.Open();
...
if (!bWasOpen)
connection.Close();
Much Worse than the crash: Your code is volunerable to Sql-injection.
--> Use parameterized sql.
The reason for this exception in the dialog is due to the connection state is already open; and hence it cannot be opened again. You must close the connection in your previous statement. Or, check if the connection closed, and then open it.
Some other tips to you is
Do not use Textbox1, Textbox2 etc., give them proper ID like txtStudentId, txtFatherName etc.,
User SQL Parameters to pass the values to your database. check the sample statements below
String query = "UPDATE submissionFee SET stdName=#stdName, fatherName=#fatherName where id=#id;";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id",txtID.txt); command.Parameters.Add("#stdName",txtStudent.Text); command.Parameters.Add("#fatherName",txtFatherName.Text);
command.ExecuteNonQuery();
Please use using statement when You query to database.
Why? Simple... it has implemented IDisposable.
P.S.
Use parameterized query to protect against SQL Injection attacks.
string insertStatement = UPDATE submissionFee SET stdName=#stdName,fatherName=#fatherName,program=#program,adress=#adress,email=#email,cellNum=#cellNum,isPaid=#isPaid,SubmissionDate=#SubmissionDate,ID=#ID
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(insertStatement, connection))
command.Parameters.AddWithValue("#ID",textBox1.Text);
command.Parameters.AddWithValue("#stdname",textbox2.Text);
command.Parameters.AddWithValue("#fathername",textBox3.Text);
command.Parameters.AddWithValue("#program",textBox4.Text);
command.Parameters.AddWithValue("#adress",textBox5.Text);
command.Parameters.AddWithValue("#email",textBox6.Text);
command.Parameters.AddWithValue("cellNum",textBox7.Text);
command.Parameters.AddWithValue("#isPaid",textBox8.Text);
command.Parameters.AddWithValue("#SubmissionDate",dateTimePicker1.Value.ToString("MM/dd/yyyy"));
connection.Open();
var results = command.ExecuteNonReader();
}
}
Part of code was taken from this link.
I'm using textbox to insert the data to the database. However I don't want to insert null or empty value to the database. How can I use if-statement to check the textbox is empty? (which means if the textbox is empty, show a dialog to required user input data)
Here is my code:
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("The Bug have been reported");
while(myReader.Read())
{
}
this.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You can use string.IsNullOrEmpty or string.IsNullOrWhiteSpace methods for checking if string is empty or only containts white spaces.
You should also avoid joining query using +. Use paratrized queries better. Example.
Try like this:
if (string.IsNullOrWhiteSpace(MyTextBox.Text))
{
//some message
}
This will handle the whitespace also (if it is present in your text box.)
On a side note:
Your code is prone to SQL Injection. You should better try to use parameterized query to handle it.
Put this condition in the start of your method
if(string.IsNullOrWhiteSpace(TextBox1.Text))
{
MessageBox.Show("Empty value");
return;
}
Use like following. Hope it will solve your problem
if(!string.IsNullOrEmpty(txtYourTextBox.Text))
{
//Logic here if text box is not empty
}
Be ware of Sql Injection
private void submit_button_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(mytextBox))
{
MessageBox.Show("your message goes here");
return ;
}
string constring = "datasource=localhost;username=root;password=";
// insert with parameterised query
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("The Bug have been reported");
while(myReader.Read())
{
}
this.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm a student programmer and I'm writing this software for a small school, it's my first program, the code below is giving me the error
syntax error in insert into statement
I know the connection string is not the problem because I use it for inserting into two other tables with the same insert into format.
I am using an access database.
The offending code is
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into studentBillRecords (StudentName, Department, Level, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) values ('"+ txtSRstudentName.Text + "', '" + cmbSRDepartment.Text + "', '" + cmbSRLevel.Text + "', '" + cmbSRAccomodationStatus.Text + "', '" + txtSRSemesterBill.Text + "', '" + txtSRPreviousBalance.Text + "', '" + txtSRTotalBill.Text + "')";
MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
connection.Close();
This same code with different table names, column names and input works with another table in the same database but won't work with this one.
Level is a reserved keyword in access.
Also use Parameters instead of concatinating string. Try this code out, it makes it safer and easier to read:
Note: I changed the name of the column Level to StudentLevel which, I assume, doesn't exist yet in your table.
try
{
using (OleDbConnection connection = new OleDbConnection("my connection string"))
{
//Open connection
connection.Open();
//Create new command
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
//Create command text
cmd.CommandText =
"INSERT INTO studentBillRecords " +
"(StudentName, Department, StudentLevel, AccomodationStatus, SemesterBill, PreviousBalance, TotalBill) VALUES " +
"(#StudentName, #Department, #StudentLevel, #AccomodationStatus, #SemesterBill, #PreviousBalance, #TotalBill)";
// Add names paremeters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#StudentName", txtSRstudentName.Text),
new OleDbParameter("#Department", cmbSRDepartment.Text),
new OleDbParameter("#StudentLevel", cmbSRLevel.Text),
new OleDbParameter("#AccomodationStatus", cmbSRAccomodationStatus.Text),
new OleDbParameter("#SemesterBill", txtSRSemesterBill.Text),
new OleDbParameter("#PreviousBalance", txtSRPreviousBalance.Text),
new OleDbParameter("#TotalBill", txtSRTotalBill.Text)
});
//Execute Query
cmd.ExecuteNonQuery();
//No need to close because we are using "using"
}
}
catch (OleDbException ex)
{
//If an exception occurs let's print it out to console
Console.WriteLine("ERROR: " + ex.ToString());
throw;
}
For information on how to change the column name read this:
https://msdn.microsoft.com/en-us/library/bb177883(v=office.12).aspx
"Level" is a keyword in MS Access, may be that is why this issue occurs try quoting it like [Level]
List Of MS Access Keywords
I am trying to pass parameters from my program to Stored Procedure in EXEC format.Following is my code
public void button1_Click(object sender, EventArgs e)
{
frm = new FrmLogin();
OleDbConnection conn = new OleDbConnection("File Name=E:\\Vivek\\License Manager\\License Manager\\login.udl");
try
{
conn.Open();
string user = username.Text;
string pass = password.Text;
string query = "EXEC dbo.checkuser"' + username.Text'" + " " + "'password.Text'"";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.ExecuteNonQuery();
// Retrieve the return value
string result = query.ToString();
MessageBox.Show(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
What should I write in string query=" "?,I am trying to pass username and password as parameters to the stored procedure and once the query executes and returns the result ,I will store it in another variable named result.Am I doing it the right way? I am new to C#
Please suggest,
Thanks
Building command text with dynamically inserted segments from user input is very dangerous, and leaves you open to SQL Injection.
Below is a slight variation which parameterizes those strings. This approach is much safer.
string query = "dbo.checkuser";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", username.Text);
cmd.Parameters.AddWithValue("#password", password.Text);
Note: This updated version sets up the command as a stored procedure, instead of plain text.
try this
OleDbCommand cmd = new OleDbCommand("StoredPorcedureName",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameter.AddWithValue("#user", username.Text);
cmd.Parameter.AddWithValue("#pwd", password.Text);
cmd.ExecuteNonQuery();
That looks Okay at a glance except for your query string. Change to:
string query = "EXEC dbo.checkuser '" + username.Text "', '" + password.Text + "'";
might work better.
Edit
Yes, as per comments about SQL injection, Troy's answer is significantly better.
Just for completeness that can be possibly used in other situations, you can avoid SQL injection using this method by trying something like:
string query = "EXEC dbo.checkuser '" + username.Text.Replace("'", "''") "', '" + password.Text.Replace("'", "''") + "'";