我正在C#.NET和MySQL中编程。我的数据库名为“ projekt1”。我创建了新表单InsertStatus.cs,其中包含:3个文本框,1个numericUpDown,2个dataTimePickers和2个复选框。
我与本地数据库有连接。我用INSERT INTO正确地编写了SQL,但是它不能写出该数据库的日期和时间。并表明这是“错误的SQL语法”。我已经尝试过 .Value.ToString()和 .Value ,但是它没有用。我想将dataTimePickers中的customFormat更改为DD-MM-YYYY HH:MM(我的意思是在正确的网站上的设置中,而不是在代码中),但是我不确定它是否可以工作。下面是这段代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace KontrolaBazaDanych
{
public partial class InsertStatus : Form
{
public InsertStatus()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;username=root;password=");
string InsertQuery = "INSERT INTO project1.status_order(ID_ORDER, ID_WORKER, ID_MODULE, AMOUNT_OF_PRODUCTS, DATE_OF_START, DATE_OF_END, ORDER_DONE, ORDER_STARTED) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + numericUpDown1.Value + "','" + dateTimePicker1.Value.ToString() + "','" + dateTimePicker2.Value.ToString() + "','" + checkBox1.ToString() + "','" + checkBox2.ToString() + "')'";
connection.Open();
MySqlCommand command = new MySqlCommand(InsertQuery, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("DATA IS ADDED.");
}
else
{
MessageBox.Show("ERROR.");
}
connection.Close();
}
// SQL COLUMNS IN status_order表:
ID_ORDER INT,
ID_WORKER INT,
ID_MODULE INT,
AMOUNT_OF_PRODUCTS INT,
DATE_OF_START DATETIME,
DATE_OF_END DATETIME,
ORDER_DONE BOOLEAN,
ORDER_STARTED BOOLEAN;
我不知道该怎么办。有人可以解释一下我该如何改变。感谢您的帮助或建议。
答案 0 :(得分:0)
您应该在代码中执行
dateTimePicker1.Value.ToString("dd-MM-YYYY hh:mm")
答案 1 :(得分:0)
也许原因是:
dateTimePicker1.Value.ToString()
即使数据库具有datetime列,您也可以将日期转换为字符串
DATE_OF_START DATETIME,
DATE_OF_END DATETIME,