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.
Related
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.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SAGAR\\SQLEXPRESS;Initial Catalog=ClinicDb;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("insert into Patient_Details (Patient Id,Name,Age,Contact No,Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "',);", con);
object o= sc.ExecuteNonQuery();
MessageBox.Show(o +"Saved data");
con .Close();
}
I see a few things;
Patient Id should be [Patient Id] and Contact No should be [Contact No] since they are more than one word. As a best practice, change their names to one word.
You have extra , at the end of textBox5.Text + "', part.
But much more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
using(var con = new SqlConnection(connection))
using(var sc = con.CreateCommand())
{
sc.CommandText = #"insert into Patient_Details ([Patient Id],Name,Age,[Contact No],Address)
VALUES(#id, #name, #age, #no, #address)";
sc.Parameters.AddWithValue("#id", textBox1.Text);
sc.Parameters.AddWithValue("#name", textBox2.Text);
sc.Parameters.AddWithValue("#age", textBox3.Text);
sc.Parameters.AddWithValue("#no", textBox4.Text);
sc.Parameters.AddWithValue("#address", textBox5.Text);
con.Open();
int i = sc.ExecuteNonQuery();
MessageBox.Show(i + " Saved data");
}
By the way, I used AddWithValue in my example since you didn't tell us your column types but you don't. This method might generate surprising results sometimes. Use Add method overloads to specify your parameter type (SqlDbType) and it's size.
Getting an object from ExecuteNonQuery is really strange as well. It will return int as an effected rows count. It will be 1 or 0 in your case.
As a last thing, I strongly suspect your Patient Id, Age and Contact No columns should be some numeric type, not character typed.
fields and table names with spaces must be inside [], also you have 1 extra comma in the end of your query. Try:
SqlCommand sc = new SqlCommand("insert into [Patient_Details] ([Patient Id],Name,Age,[Contact No],Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "');", con);
object o= sc.ExecuteNonQuery();
also consider using parameters, since you are open to sql injection.
I am working on a Desktop application. I developed a form in which user enters data. When he clicks the submit button the data is saved in a database name PakReaEstat. The problem is the data is not inserted in the table and I get an error: SqlException was Unhandled.
When I click the Submit button it prompts error.
The code behind the button is as following:
protected void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo");
con.Open();
SqlCommand cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime)" +
"values (" + Convert.ToInt32(textBox1.Text) + ",'" +
textBox2.Text + "','" +
textBox4.Text + "'," +
textBox5.Text + "," +
textBox6.Text + "," +
textBox7.Text + "," +
textBox8.Text +
"," + textBox3.Text + ")", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Insertion successfully done");
}
Check you connection string and the SQL insert statement.
I recommend that you use sql parameters instead of the the textbox text property as value directly.
Beacause this is a common vulnerability, called SQL injection.
I also recommend to use using statement to ensure the connection is closed.
using (var con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo"))
{
con.Open();
using (var cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime)" + "values (#Application#,#LDAReg#, ... )", con))
{
cmd.Parameters.AddWithValue("#Application#", Convert.ToInt32(textBox1.Text));
cmd.Parameters.AddWithValue("#LDAReg#", textBox2.Text);
// add the other parameters ...
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Insertion successfully done");
There is problem in your SqlConnection
Make sure that your connection string is correct
SqlConnection con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo");
It should come like
SqlConnection con = new SqlConnection("Data Source=ADMIN3-PC;Initial Catalog=master;Integrated Security=True");
Always put your code in try... catch block if you are doing transaction with datatbase
If your connetion to databse is established and no issue there then
You are missing single quotes on last five textboxes. I suppose that last five columns are of type nvarchar in ur datatbse
change command to
SqlCommand cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime) values (" + Convert.ToInt32(textBox1.Text) + ",'" + textBox2.Text + "','" + textBox4.Text + " ','" + textBox5.Text + "','" + textBox6.Text+ "','" +textBox7.Text+ "','"+textBox8.Text +"','"+textBox3.Text+"')", con);
private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection connection = new SqlCeConnection(" Data Source=|DataDirectory|\\Database1.sdf; Persist Security Info=False ;");
connection.Open();
MessageBox.Show("Connection successful");
//listBox1.SelectedItem.ToString();
SqlCeCommand command = new SqlCeCommand("insert into malware (malwarename, threatlevel,malwaretype,kind,Description,Reg,network,developer,exportfix,date,id,signature)VALUES ('" + textBox1.Text + " ' , ' " + listBox1.SelectedItem + " ', '" + listBox2.SelectedItem + "' , '" + listBox3.SelectedItem + "', '" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox8.Text + "','" + dateTimePicker1.Value.Date.ToShortDateString() + "','" + textBox6.Text + "','" + textBox7.Text + "');", connection);
MessageBox.Show("fine till here ");
//SqlCeDataReader reader = command.ExecuteQuery();
//reader.Close();
int m = command.ExecuteNonQuery();
MessageBox.Show(m .ToString());
connection.Close();
}
Why my queries not updated on apply when I check?
Well, you didn't tell us do you have an error or not, here is the right way to do it.
First, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Second, you should dispose your connection with using keyword.
To ensure that connections are always closed, open the connection
inside of a using block, as shown in the following code fragment.
Doing so ensures that the connection is automatically closed when the
code exits the block.
Third, DATE could be reserved keyword in future releases of SQL Server. You might need to use it with square brackets like [DATE]. As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Here is an example;
private void button1_Click(object sender, EventArgs e)
{
using(SqlCeConnection connection = new SqlCeConnection("Data Source=|DataDirectory|\\Database1.sdf; Persist Security Info=False;"))
{
SqlCeCommand command = new SqlCeCommand("insert into malware (malwarename, threatlevel,malwaretype,kind,Description,Reg,network,developer,exportfix,[date],id,signature)
VALUES(#malwarename, #threatlevel, #malwaretype, #kind, #Description, #Reg, #network, #developer, #exportfix, #date, #id, #signature)",
connection);
command.Parameters.AddWithValue("#malwarename", textBox1.Text);
command.Parameters.AddWithValue("#threatlevel", listBox1.SelectedItem.ToString());
command.Parameters.AddWithValue("#malwaretype", listBox2.SelectedItem.ToString());
command.Parameters.AddWithValue("#kind", listBox3.SelectedItem.ToString());
command.Parameters.AddWithValue("#Descriptione", textBox2.Text);
command.Parameters.AddWithValue("#Reg", textBox3.Text);
command.Parameters.AddWithValue("#network", textBox4.Text);
command.Parameters.AddWithValue("#developer", textBox5.Text);
command.Parameters.AddWithValue("#exportfix", textBox8.Text);
command.Parameters.AddWithValue("#date", dateTimePicker1.Value.Date.ToShortDateString());
command.Parameters.AddWithValue("#id", textBox6.Text);
command.Parameters.AddWithValue(" #signature", textBox7.Text);
connection.Open();
int m = command.ExecuteNonQuery();
MessageBox.Show(m.ToString());
connection.Close();
}
}
Are you sure your checked database is your updated database ?
And then, Maybe you can put code statement of try-catch-finally ,check your app maybe throw some exception has occurred, try it!
I have to execute a query of insertion in my c# code
connexion = new SqlConnection(connexionString);
connexion.Open();
List<int> liste = client.GetIDFichiers(1210);
int a = 2;
foreach (int idfichier in liste)
{
a++;
using (connexion)
{
using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO REL_Fab3DLotFichier_Fichier3D (IDREL_Fab3DLotFichier_Fichier3D,IDFichier3D,IDFab3DLotFichier,CreePar,CreeLe,ModifiePar,DateMaj,EstActif) VALUES (" + a + "," + idfichier + "," + 17965 + "," + null + "," + null + "," + null + "," + null + "," + 1 + ")", connexion))
{
try
{
sqlCmd.ExecuteNonQuery();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
}
}
The insertion isn't working and i don't know why. the selection and delete queries worked fine. Only when i try to insert values a syntaxic error appears.
what is the syntax error?
How can i fix it?
what is the syntax error? and How can i fix it?
Yes. Use parameterized SQL statement.
string sql = "INSERT INTO TableName (Column1,Column2) VALUES (#value1,#value2)";
using(SqlCommand sqlCmd = new SqlCommand(sql,connection))
{
sqlCmd.Parameters.Add("#value1",SqlDbType.Varchar,20).Value = varName1;
sqlCmd.Parameters.Add("#value2",SqlDbType.Varchar,20).Value = DBNull.Value;
...
}
Try to include not null fields to prepare INSERT SQL.
sql=#"INSERT INTO REL_Fab3DLotFichier_Fichier3D
(IDREL_Fab3DLotFichier_Fichier3D,
IDFichier3D,
IDFab3DLotFichier,
DateMaj,EstActif)
VALUES
(#IDREL_Fab3DLotFichier_Fichier3D,
#IDFichier3D,
#IDFab3DLotFichier,
#DateMaj,#EstActif)";
Some of the values you are passing may be string/varchar objects and you aren't wrapping them with quotes:
new SqlCommand("INSERT INTO REL_Fab3DLotFichier_Fichier3D (IDREL_Fab3DLotFichier_Fichier3D,IDFichier3D) VALUES ('" + a + "', '" + idfichier + "')", connexion);
Really, as AVD suggested, you should use parameterisation, which is less prone to injection attacks.
please enclose your string values in single quotes like below
New SqlCommand("insert into Type(TypeName,TypeOrder,CategoryID) values ('" + txtType1.Text + "','" + txtOrder.Text + "','" + ViewState("CatID").ToString() + "')", con)