在SQL数据库中插入Datetimepicker文本

时间:2010-06-30 07:35:54

标签: c# sql

如何在SQL数据库中将Datetimepicker文本作为datetime数据类型

插入

3 个答案:

答案 0 :(得分:2)

要从datetime选择器解析日期时间,您可以执行以下操作:

string dt = dateTimePicker.Value.ToString("yyyy-MM-dd hh:mm:ss");

然后,为了将其插入您的数据库,您可以执行以下操作:

Insert into table (id, mytime) 
values("5",  CONVERT(datetime, CONVERT( varchar(11), dt, 101))

如果您需要有关如何访问数据库的信息,请阅读以下article in CodeProject

答案 1 :(得分:0)

解析C#中的文本,然后插入解析后的DateTime。例如:

var date = new DateTime(dateTimePickerText);
InsertIntoSqlDatabase(date); // Code for inserting here.

答案 2 :(得分:0)

您可以使用DateTime直接将日期DataRow插入(不转换为字符串)。 例如:

  using (SqlConnection sqlconn = new SqlConnection())
        {
            sqlconn.ConnectionString = @"Data Source = #your_serwer\instance#; Initial Catalog = #db_name#; User Id = #user#; Password = #pwd#;";
            sqlconn.Open();

            // select your date and a key index field on a table (e.g. "id")
            string sql = "select id, some_date from table_1 where id = 1 ";

            using (SqlDataAdapter adapter = new SqlDataAdapter(sql, sqlconn))
            {
                using (DataTable table = new DataTable())
                {
                    adapter.Fill(table);                       

                    DataRow r = null;
                    if (table.Rows.Count == 1)
                        r = table.Rows[0];   // case, when there is an row for update
                    else
                        r = table.NewRow();  // case, when there is no row, and you would like to insert one

                    r.BeginEdit();
                    // here you assign your value
                    r["some_date"] = dateTimePicker.Value;
                    r.EndEdit();

                    if (table.Rows.Count == 0)
                    {
                        // in case of insert, provide here some other values for other non null columns like
                        r["id"] = 2;
                        // also you have to add this row into DataTable
                        table.Rows.Add(r);
                    }

                    // this will update the database
                    SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(adapter);
                    adapter.Update(table);
                }
            }
        }

希望,这有帮助。