I have made a small application that automatically inserts data from datagridview into a MySQL table by clicking a button. My problem is that after pasting into MySQL table some data is simply truncated because it has more strings than the table allows. This happens without me noticing and I am looking for a solution. Simply increasing the number of strings in MySQL is not a solution. At the end, only data records should be saved that have really not been shortened automatically. Thanks
here is my code:
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0 ; i < dataGridView1.Rows.Count - 1; i++) // dòng
{
string str = "server=xxxx; database=xxxx; uid=xxxx; pwd=xxxxxx;";
MySqlConnection constr = new MySqlConnection(str);
constr.Open();
String cmdText = "INSERT INTO table (spalte1, spalte2, spalte3) VALUES ('"
+ dataGridView1.Rows[i].Cells[0].Value + "','"
+ dataGridView1.Rows[i].Cells[1].Value + "','"
+ Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value).ToString("yyyy-MM-dd HH:mm:ss.fff") + "','"
+ dataGridView1.Rows[i].Cells[3].Value + "')";
MySqlCommand cmd = new MySqlCommand(cmdText, constr);
cmd.ExecuteNonQuery();
constr.Close();
}
}
You want to set the SQL Mode of MySQL to Traditional . This will enable Strict SQL Mode , which will raise an error when data is truncated during insert or update.
As others have commented, a user-friendly approach is to additionally make the users aware of the limit before they try to store data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.