如何使用c#将year作为参数传递给SQL查询

本文关键字:参数传递 SQL 查询 何使用 year | 更新日期: 2023-09-27 18:05:01

我在尝试传递年份作为参数时遇到了一个问题。我得到

从字符串

转换日期和/或时间失败

见下面的代码

"SELECT distinct [study_patient_name],[study_patient_prenom] " +
"FROM examen where study_traitant_id='" + GridView1.SelectedRow.Cells[1].Text.Trim() + "'  "+
"and study_description ='"+GridView1.SelectedRow.Cells[7].Text.Trim()+ "' "+
"and study_rv_date between ('01/01/@date1')  ('31/12/@date2')" +
"order by [study_patient_name] asc ", myConnection);
myCommand.Parameters.AddWithValue("@date1", txtdate1.Text);
myCommand.Parameters.AddWithValue("@date2", txtdate2.Text);  

如何使用c#将year作为参数传递给SQL查询

您知道如何参数化查询(您已经使用了2个参数),因此没有理由使用字符串连接—这是一个安全漏洞。一个大的!

除此之外,您正在寻找给定YEAR s范围内的任何日期。这里有一个函数!

"and YEAR(study_rv_date) BETWEEN @date1 AND @date2 "

传递整数作为年份

你应该学会参数化你的查询。你的代码应该是这样的:

string sql = "SELECT DISTINCT [study_patient_name],[study_patient_prenom] " +
        "FROM examen WHERE study_traitant_id = @study_traitant_id " +
        "AND study_description = @study_description " +
        "AND study_rv_date BEWTWEEN @date1 AND @date2 " +
        "ORDER BY [study_patient_name]";
var myCommand = new System.Data.SqlClient.SqlCommand(sql, myConnection);
myCommand.Parameters.Add("@study_traitant_id", SqlDbType.VarChar, 50).Value = GridView1.SelectedRow.Cells[1].Text.Trim();
myCommand.Parameters.Add("@study_description", SqlDbType.VarChar, 50).Value = GridView1.SelectedRow.Cells[7].Text.Trim();
myCommand.Parameters.Add("@date1", SqlDbType.Date).Value = new DateTime(year, 1, 1);
myCommand.Parameters.Add("@date2", SqlDbType.Date).Value = new DateTime(year, 12, 31);

year是作为参数传递的变量,您将从txtDate1txtDate2获得该变量。为了获得开始日期,我使用:

new Datetime(year, 1, 1);

和结束日期:

new Datetime(year, 12, 31);

您可以根据自己的喜好使用其他函数。

额外注意,最好使用Parameters.Add而不是AddWithValue。根据这篇文章:

AddWithValue()函数有一个问题:它必须推断查询参数的数据库类型。事情是这样的:有时它会出错。

从c#传递如下参数:

        myCommand.CommandText = @"
            SELECT DISTINCT
                [study_patient_name], [study_patient_prenom] 
            FROM 
                [examen]
            WHERE 
                [study_traitant_id] = @TraitantId
                AND
                [study_description] = @Description
                AND
                [study_rv_date] BETWEEN @StartOfYear AND @EndOfYear
        ";
        // Send Parameters
        myCommand.Parameters.AddWithValue("TraitantId", GridView1.SelectedRow.Cells[1].Text.Trim());
        myCommand.Parameters.AddWithValue("Description", GridView1.SelectedRow.Cells[7].Text.Trim());
        myCommand.Parameters.AddWithValue("@StartOfYear", new DateTime(int.Parse(txtdate1.Text), 1, 1));
        myCommand.Parameters.AddWithValue("@EndOfYear", new DateTime(int.Parse(txtdate2.Text), 12, 31));