我用下面的代码从一个日期到另一个日期记录 [英] i used the below code to from one date to another date records

查看:89
本文介绍了我用下面的代码从一个日期到另一个日期记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable(); SqlDataAdapter sda = new SqlDataAdapter("Select * from patient where Date between '" + dateTimePicker1.Text + "' and '" + dateTimePicker2.Text + "'", myconnection);
sda.Fill(dt);
dataGridView1.DataSource = dt;

        }



任何人都可以帮助我单击一个日期到另一个日期记录的问题吗?

预先感谢



can anyone help whats the problem when i am clicking to see from one date to another date records

thanks in advance

推荐答案

主要问题是您将值直接连接到SQL语句.由于您依赖从字符数据到日期时间的隐式转换,因此这使您可以进行SQL注入,并且还会引起问题.

解决方法是使用参数.换句话说,您的代码应类似于
The main problem is that you concatenate the values directly to the SQL statement. This leaves you wide open to SQL injections and also causes problems since you''re relying on implicit conversion from character data to datetime.

The cure is to use parameters. In other words your code should look something like
DataTable dt = new DataTable(); 
SqlCommand sc = new SqlCommand();
sc.CommandText = "Select * from patient where Date between @date1 and @date2";
sc.Connection = myconnection;
sc.Parameters.AddWithValue("@date1", dateTimePicker1.Value);
sc.Parameters.AddWithValue("@date2", dateTimePicker2.Value);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = sc;
sda.Fill(dt);
dataGridView1.DataSource = dt;


(很抱歉输入错误)

另外,您应该使用using块来确保正确处理命令,连接等.

我还建议您阅读正确执行数据库操作 [


(Sorry for possible typos)

Also you should use using blocks to ensure proper disposal of commands, connections and so on.

I''d also recommend reading Properly executing database operations[^]


对于初学者,不要那样做!不要连接字符串以构建SQL命令.它使您对意外或蓄意的SQL注入攻击敞开大门,这可能会破坏整个数据库.请改用参数化查询.
For starters, stop doing it like 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.
private void button1_Click(object sender, EventArgs e)
        {
        DataTable dt = new DataTable(); 
        SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM patient WHERE [Date] BETWEEN @ST AND @EN", myconnection);
        sda.SelectCommand.Parameters.AddWithValue("@ST", dateTimePicker1.Value);
        sda.SelectCommand.Parameters.AddWithValue("@EN", dateTimePicker2.Value);
        sda.Fill(dt);
        dataGridView1.DataSource = dt;
        }

有机会同时解决您的问题.

[edit]错别字:在第二个参数行中为"@EN"写了"@ED".[/edit]

The chances are that will solve your problem at the same time.

[edit]Typo: wrote "@ED" for "@EN" in the second parameter line.[/edit]


这篇关于我用下面的代码从一个日期到另一个日期记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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