SQL表编辑:在表中添加DateTime值
本文关键字:添加 DateTime 编辑 SQL | 更新日期: 2023-09-27 18:30:11
我制作了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"设置为DateTime。非常感谢。
"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)";
如果ban_date
列是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)";