从字符串转换日期和/或时间时转换失败。在c#中 [英] Conversion failed when converting date and/or time from character string. in c#

查看:395
本文介绍了从字符串转换日期和/或时间时转换失败。在c#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void btn_BooksList_Click(object sender, EventArgs e)
       {
           FRM_ReservationList frm = new FRM_ReservationList();


           con.Open();
           s = " select R.P_id, Patients.P_Name,Total_Reservation Date_Reservation   ,  R.Notes from ResrvationData R  
           s = s + " where  Date_Reservation = '" + dateTimePicker_Time.Text + "' ";
           s = s + " order by Date_Reservation desc , Total_Reservation ";
           sCommand = new SqlCommand(s, con);
           sdAdapter = new SqlDataAdapter();
           sdAdapter.SelectCommand = sCommand;
           dt = new DataTable();
           sdAdapter.Fill(dt);
           //BindingSource BSource = new BindingSource();
           //BSource.DataSource = dt;
           frm.dataGridView_ReservationList.DataSource = dt;
           con.Close();
           frm.ShowDialog();

       }





我的尝试:



如何为这个问题找到解决方案



What I have tried:

How i can find solution for this problem

推荐答案

首先,停止这样做。

不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。

在这种情况下,该代码不容易受到SQL注入的影响,但它可能会失败,因为SQL不知道用户所在的语言环境,并试图猜测转换时的实际日期格式是什么。

如果直接将DateTimePicker.Value属性作为参数传递,那么它不需要在任何方向上进行转换,而SQL只是得到正确的值立即。

First off, stop doing that.
Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
In this case, that code isn't vulnerable to SQL injection, but it is likely to fail because SQL doesn't know what locale the user is in, and tries to "guess" what the actual date format is when it does the convert.
If you pass the DateTimePicker.Value property directly as a parameter, then it needs no conversion in any direction, and SQL just gets the correct value immediately.
s = " SELECT R.P_id, Patients.P_Name,Total_Reservation Date_Reservation   ,  R.Notes FROM ResrvationData R ";
s = s + " WHERE Date_Reservation = @DR ";
s = s + " ORDER BY Date_Reservation desc , Total_Reservation ";
sCommand = new SqlCommand(s, con);
sCommand.Parameters.AddWithValue("@DR", dateTimePicker_Time.Value);


这篇关于从字符串转换日期和/或时间时转换失败。在c#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆