我試圖從datGridView到SQL Server插入數據(我從一個Excel文件加載數據)。但是我得到一個主鍵錯誤,它不應該爲空。C#的dataGridView到SQL(插入)
如果我用這樣的:
cmd.Parameters.AddWithValue("@id", 1012);
它返回一個重複鍵錯誤...
這是我的代碼:
private void btnTest_Click(object sender, EventArgs e)
{
int stCol = dataGWseznam.Columns.Count;
string[] poljeNaslovov = new string[dataGWseznam.Rows.Count];
for (int i = 0; i < stCol; i++)
{
poljeNaslovov[i] = Convert.ToString(dataGWseznam.Columns[i].HeaderText);
}
string[] poljeNaslovovAfna = new string[dataGWseznam.Rows.Count];
for (int i = 0; i < stCol; i++)
{
poljeNaslovovAfna[i] ="@" + Convert.ToString(dataGWseznam.Columns[i].HeaderText);
}
string msg1 = String.Join(",", poljeNaslovov.Where(s => !string.IsNullOrEmpty(s)));
string msg2 = String.Join(",", poljeNaslovovAfna.Where(s => !string.IsNullOrEmpty(s)));
try
{
foreach (DataGridViewRow row in dataGWseznam.Rows)
{
string constring = @"MY DATA SOURCE";
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Monitoring(id,date,time) VALUES(@id,@date,@time)", conn))
{
cmd.Parameters.AddWithValue("@id", 1012);
cmd.Parameters.AddWithValue("@date", row.Cells["date"].Value);
cmd.Parameters.AddWithValue("@time", row.Cells["time"].Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
catch (Exception ex)
{
//handle exception
MessageBox.Show(ex.Message);
}
MessageBox.Show("Done.");
}
我該如何解決這個問題?
你用相同的ID對所有行cmd.Parameters.AddWithValue( 「@ ID」,1012); 你必須實現一些東西來allcate不同主鍵 –