簡體   English   中英

C#從DataGridView插入MySQL數據后被截斷

[英]C# After inserting from DataGridView into MySQL data are truncated

我創建了一個小應用程序,通過單擊按鈕自動將數據從datagridview插入到MySQL表中。 我的問題是,在粘貼到MySQL表之后,一些數據被簡單地截斷,因為它有比表允許的字符串更多的字符串。 這種情況在我沒有注意到的情況下發生,我正在尋找解決方案。 簡單地增加MySQL中的字符串數量不是解決方案。 最后,只保存實際上沒有自動縮短的數據記錄。 謝謝

這是我的代碼:

 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();
        }

    }

您希望將MySQL的SQL模式設置為傳統 這將啟用嚴格SQL模式 ,這將在插入或更新期間截斷數據時引發錯誤。

正如其他人所評論的那樣,用戶友好的方法是在用戶嘗試存儲數據之前另外讓用戶知道限制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM