2016-08-14 45 views
-1

在我的應用程序中,我有一個dataGridview,它有一個從數據庫中獲取其數據的列,它表示一個類型爲date的列,當用戶單擊它時會有一個按鈕,它應該插入當前的選擇值另一個表中有一列類型爲日期的列。 我嘗試這樣做的那樣:從DataGridView插入到數據庫中的日期?

private void btnInesrtDate_Click(object sender, EventArgs e) 
     { 
      string date = dataGridView1.CurrentRow.Cells[2].ToString(); 
      string sql = $"Insert Into BirthDates (Name, DateOfBirth)Values('{txtName.Text}','{date}')"; 
      conn.Open(); 
      SqlCommand command = new SqlCommand(sql, conn); 
      command.ExecuteNonQuery(); 
      conn.Close(); 
      MessageBox.Show("Success"); 
     } 

,但我得到了一個錯誤說:從文字 字符串轉換日期和/或時間時

轉換失敗。

回答

1

您使用的語法不正確,需要修復。您當前只是指定一些硬編碼的值......它不能將字符串文字'{date}'解析爲DateTime。

使用參數安全地將值傳遞給您的查詢。這是未經測試,但應該工作(讀太多的評論):

private void btnInesrtDate_Click(object sender, EventArgs e) 
{ 
    string sql = "Insert Into BirthDates (Name, DateOfBirth) Values (@Name, @BirthDate)"; 

    // Always parameterize your query... it's more secure and less prone to errors 
    DateTime birthday = Convert.ToDateTime(dataGridView1.CurrentRow.Cells[2].Value); 
    command.Parameters.AddWithValue("@Name", txtName.Text); 
    command.Parameters.AddWithValue("@BirthDate", birthday); 

    conn.Open(); 

    // Use a Try/Finally block to so the connection is closed even if an exception occurs 
    try 
    { 
     using (var command = new SqlCommand(sql, conn)) 
     { 
      command.ExecuteNonQuery(); 
      MessageBox.Show("Success"); 
     } 
    } 
    finally 
    { 
     conn.Close(); 
    } 
} 
+0

我得到了同樣的錯誤:( –

+0

試試這個:'日期時間生日= Convert.ToDateTime(dataGridView1.CurrentRow.Cells [2] .value的);' –

+0

好吧,它現在可以工作了我發現我在轉換爲字符串之前忘記了value屬性,但是我有一個問題,這是否意味着SQL中的日期類型只接受DateTime對象,並且不能接受字符串?我記得我以前做過! –

0

查詢看起來不正確,嘗試從查詢中刪除多餘的'{',如果來自UI的日期格式正確,它應該沒問題。請參閱下面的代碼示例:

SqlConnection conn = new SqlConnection(@"Connection String;"); 

    string date = DateTime.Now.ToString("MM/dd/yyyy"); 
    string sql = $"Insert Into BirthDates (Name, DateOfBirth)Values('" + txtName.Text + "','" + date +"')"; 
    conn.Open(); 
    SqlCommand command = new SqlCommand(sql, conn); 
    command.ExecuteNonQuery(); 
    conn.Close();