0

我制作了 SQL 表编辑器以在某些列中添加信息。但是其中一列设置为“DateTime”,应用程序无法写入。这是代码:

private void button2_Click(object sender, EventArgs e)
    {


try

{
    string connectionString = @"Data Source=" + textBox4.Text + ";" + "Initial Catalog=" + textBox1.Text + ";" + "User ID=" + textBox2.Text + ";" + "Password=" + textBox3.Text;
    using (SqlConnection connection = new SqlConnection(connectionString))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end) VALUES (@char_id, @status, DateTime @ban_date, @ban_hour, @ban_end)";

        command.Parameters.AddWithValue("@char_id", "1");
        command.Parameters.AddWithValue("@status", "1");          
        command.Parameters.AddWithValue("@ban_date", "1");
        command.Parameters.AddWithValue("@ban_hour", "1");
        command.Parameters.AddWithValue("@ban_end", "1");              
        connection.Open();
        command.ExecuteNonQuery();
        MessageBox.Show("Char Banned");
    }
}
catch (SqlException ex)
{
   MessageBox.Show(ex.Message);
}
}

列“ban_date”设置为日期时间。谢谢!

4

2 回答 2

4

"1"不是日期。尝试将日期传递给它

command.Parameters.AddWithValue("@ban_date", DateTime.Today);

DateTime从命令字符串中删除

command.CommandText = "INSERT INTO user_ban 
                      (char_id, status, ban_date, ban_hour, ban_end) 
                      VALUES 
                      (@char_id, @status, @ban_date, @ban_hour, @ban_end)";
于 2013-09-04T10:56:04.183 回答
0

如果ban_datecolumn is DateTime,为什么要插入1它?没有意义。1根本不是有效DateTime的。将其更改为有效值DateTime

其次,你不应该在你的VALUES部分使用值类型。改变它从

command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end)
                       VALUES (@char_id, @status, DateTime @ban_date, @ban_hour, @ban_end)";
                                                  ^^^^^^^^^//delete this

command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end)
                       VALUES (@char_id, @status, @ban_date, @ban_hour, @ban_end)";
于 2013-09-04T10:58:53.467 回答