Run the SQL command with single quotes in C #.
SQL command: string selectCmd = "select * from score where name = '" + textBox1.Text + "'";
An exception is reported when you directly enter a string containing single quotes in textBox1.
Cause: SQL treats data enclosed by single quotes as strings, while data enclosed by double quotes is treated as strings by C #. NET.
For example:
String selectCmd = "select * from score where name = '" + "AB 'C" + "'";
After C #. NET is compiled, it becomes:
Select * from score where name = 'AB 'c'
When SQL syntax is executed, AB is treated as a string (AB is enclosed by single quotes), while c 'data is incorrect because a single quotation mark is missing.
Solution:
In SQL syntax, two single quotes ("'' ") are considered as one single quotation mark. Therefore, you can use the Replace method of the String class to Replace one of the strings.
Replace single quotes with two single quotes.
For example:
String selectCmd = "select * from tbname where fieldname = '" + textBox1.Text + "'";
Changed:
String selectCmd = "select * from tbname where fieldname = '" + textBox1.Text. Replace ("'", "'' ") + "'";
Example:
Compare the following statements:
String sql0 = "insert into tbBattery_InfoD (Battery_Voltagedouble, Battery_Electricaldouble, Battery_Datedtm) VALUES (" + dataGridView1.Rows [iCCC + 1]. cells [2]. value. toString () + "," + dataGridView1.Rows [iCCC + 1]. cells [5]. value. toString () + "," + "'" + datetime + "'" + ")";
String sql1 = "insert into tbBattery_InfoD (Battery_Voltagedouble, Battery_Electricaldouble, Battery_Datedtm) VALUES (" + dataGridView1.Rows [iCCC + 1]. cells [2]. value. toString () + "','" + dataGridView1.Rows [iCCC + 1]. cells [5]. value. toString () + "'," + "'" + datetime + "'" + ")";
The Battery_Voltagedouble and Battery_Electricaldouble fields are set to float and dataGridView1.Rows [iCCC + 1]. cells [5]. value. toString () and dataGridView1.Rows [iCCC + 1]. cells [5]. value. when ToString () is null, the first statement is incorrect. The second statement can be executed and the inserted value is 0.