【问题标题】:Inserting date from DataGridView into database?将 DataGridView 中的日期插入数据库?
【发布时间】:2016-08-14 00:29:39
【问题描述】:

在我的应用程序中,我有一个 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");
        }

但我得到一个错误说:

从字符转换日期和/或时间时转换失败 字符串。

【问题讨论】:

    标签: c# sql datagridview


    【解决方案1】:

    您使用的语法不正确,需要修正。您当前只是指定了一些硬编码值...它无法将字符串文字 '{date}' 解析为 DateTime。

    使用参数安全地将值传递给您的查询。这是未经测试的,但应该可以工作(也阅读 cmets):

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

    【讨论】:

    • 嗯,现在可以了。我发现我在转换为字符串之前忘记获取 value 属性,但是我有一个问题,这是否意味着 SQL 中的日期类型只接受 DateTime 对象,而不能接受字符串?我记得我以前做过!
    【解决方案2】:

    查询看起来不正确,请尝试从查询中删除额外的“{”,如果来自 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();
    

    【讨论】:

      猜你喜欢
      • 2011-04-06
      • 1970-01-01
      • 2016-04-22
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多