如何将 DateTimepicker 值转换为日期数据类型?

How to convert DateTimepicker value to date datatype?

我的数据库是:

create table bus
( bus_no varchar(10),
  jdate date,
  source varchar(20),
  destination varchar(20),
  departtime varchar(10),
  primary key(bus_no,jdate));

C#

c.connect();
comm = new OracleCommand(); /*Class OracleCommand  represents an SQL statement or stored procedure to execute against a database. OracleCommand() initializes a new instance of the OracleCommand. */
comm.Connection = c.conn;
//Console.Write(dateTimePicker1.Value.ToShortDateString());
comm.CommandText = "INSERT INTO bus VALUES ('" + busno.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "','" + source.Text + "','" + destination.Text + "','" + departtime.Text + "')";
comm.CommandType = CommandType.Text;
MessageBox.Show("Bus Added");
comm.ExecuteNonQuery();
c.conn.Close();

显示错误,因为无法识别月份。请帮忙。

您可以使用自定义格式化程序将其格式化为正确的格式。通常默认的 C# 短字符串不适用于 Oracle。

dateTimePicker1.Value.ToString("MM/dd/yyyy")

dateTimePicker1.Value.ToString("M/d/yyyy")

您永远不应在应用程序中使用串联的 SQL 字符串。参数化查询会更快,并帮助您避免 SQL Injection 和类型转换的麻烦。

c.connect();
comm = new OracleCommand(); /*Class OracleCommand  represents an SQL statement or stored procedure to execute against a database. OracleCommand() initializes a new instance of the OracleCommand. */
comm.Connection = c.conn;
comm.CommandText = "INSERT INTO bus VALUES (:bus_no, :jdate, :source, :destination, :departtime)";
comm.Parameters.Add("bus_no",  busno.Text);
comm.Parameters.Add("jdate", dateTimePicker1.Value);
comm.Parameters.Add("source", source.Text);
comm.Parameters.Add("destination", destination.Text);
comm.Parameters.Add("departtime", departtime.Text);
comm.ExecuteNonQuery();
MessageBox.Show("Bus Added");
c.conn.Close();