简体   繁体   English

如何在 C# 中进行参数化 SELECT 查询?

[英]How to make a parameterized SELECT query in C#?

I'm trying to display data from a table in database using DataGridView and a parameterized query in C# and SQL Server.我正在尝试使用 DataGridView 和 C# 和 SQL Server 中的参数化查询显示数据库表中的数据。

So far, I have tried this code:到目前为止,我已经尝试过这段代码:

private void button1_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True");

        SqlCommand cmd = new SqlCommand("SELECT Ansatte.ansatID = @ansat, Ansatte.Navn = @navn, Ansatte.Efternavn = @efternavn, Ansatte.Adresse = @adresse, Ansatte.Postnummer = @postnummer, Ansatte.Bynavn = @bynavn, Ansatte.Email = @email, Ansatte.Mobilnr = @mobilnr, Login_data.Brugertype = @brugertype FROM Ansatte INNER JOIN Login_data ON Ansatte.ansatID = Login_data.ansatID", con);

        cmd.Parameters.Add("@ansat", SqlDbType.Int);
        cmd.Parameters.Add("@navn", SqlDbType.VarChar);
        cmd.Parameters.Add("@eftervavn", SqlDbType.VarChar);
        cmd.Parameters.Add("@adresse", SqlDbType.VarChar);
        cmd.Parameters.Add("@postnummer", SqlDbType.Int);
        cmd.Parameters.Add("@bynavn", SqlDbType.VarChar);
        cmd.Parameters.Add("@email", SqlDbType.VarChar);
        cmd.Parameters.Add("@mobilnr", SqlDbType.Int);
        cmd.Parameters.Add("@brugertype", SqlDbType.VarChar);

        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        dataGridView2.DataSource = dt;
    }

But I get the following error:但我收到以下错误:

Incorrect syntax near '=' '=' 附近的语法不正确

How to fix it so I can select data using a parameterized query?如何修复它以便我可以使用参数化查询选择数据? Expected result is, that data will be displayed in a DataGridView.预期的结果是,该数据将显示在 DataGridView 中。

You have a few things going on here, and I'll try to break down for you.你有一些事情在这里发生,我会尽力为你打破。 Working with a database, you typically do a "select...from..." to get data and "insert into..." to add records to the tables.使用数据库时,您通常执行“select...from...”以获取数据并“insert into...”以将记录添加到表中。

Next, your query.接下来,您的查询。 A shortened version of yours.. The problem here is you are trying to assign the @ansat PARAMETER value INTO the Ansatte.ansatID field which is incorrect syntax context to begin with, but review on regardless.你的一个缩短版本.. 这里的问题是你试图将@ansat PARAMETER 值分配到 Ansatte.ansatID 字段中,这是开始时不正确的语法上下文,但无论如何都要查看。

SqlCommand cmd = new SqlCommand(
@"SELECT 
      Ansatte.ansatID = @ansat, 
      Ansatte.Navn = @navn, 
      Ansatte.Efternavn = @efternavn, 
      Ansatte.Adresse = @adresse...
   FROM 
      Ansatte 
         INNER JOIN Login_data 
            ON Ansatte.ansatID = Login_data.ansatID", con);

and then adding the parameters...然后添加参数...

cmd.Parameters.Add("@ansat", SqlDbType.Int);
cmd.Parameters.Add("@navn", SqlDbType.VarChar);
cmd.Parameters.Add("@eftervavn", SqlDbType.VarChar);
cmd.Parameters.Add("@adresse", SqlDbType.VarChar);

Good you are using parameters, but you just DECLARED the parameters, you never assigned any actual values to them, which in essence is resulting in the following getting passed to the engine很好,您正在使用参数,但是您只是声明了参数,您从未为它们分配任何实际值,这实质上导致以下内容传递给引擎

SELECT 
      Ansatte.ansatID = , 
      Ansatte.Navn = , 
      Ansatte.Efternavn = , 
      Ansatte.Adresse = 
   FROM 
      Ansatte 
         INNER JOIN Login_data 
            ON Ansatte.ansatID = Login_data.ansatID

Hence probably your error for no value for the = sign.因此,您的错误可能是 = 符号没有价值。 Now, to actually add the "Value" to your parameter... Your declaration appeared ok, just finish it with a value that could be a fixed value, from a window entry, config setting, whatever...现在,要实际将“值”添加到您的参数中...您的声明看起来没问题,只需使用一个可以是固定值的值来完成它,来自窗口条目、配置设置等等...

cmd.Parameters.Add("@ansat", SqlDbType.Int).Value = 123;
cmd.Parameters.Add("@navn", SqlDbType.VarChar).Value = "test";
cmd.Parameters.Add("@eftervavn", SqlDbType.VarChar).Value = "more";
cmd.Parameters.Add("@adresse", SqlDbType.VarChar).Value = "done";

which would result in a protected (non-sql-injection)这将导致受保护的(非 sql 注入)

Now, what you might really be looking for.现在,您可能真正在寻找什么。 You have a table in your database that you want to pull information from.您的数据库中有一个要从中提取信息的表。 In this case, select the columns you WANT, not the values you want to SET.在这种情况下,请选择您想要的列,而不是您想要设置的值。 Just query.只是查询。 Ex:前任:

SqlCommand cmd = new SqlCommand(
@"SELECT 
      Ansatte.ansatID, 
      Ansatte.Navn, 
      Ansatte.Efternavn, 
      Ansatte.Adresse, 
      Ansatte.Postnummer, 
      Ansatte.Bynavn, 
      Ansatte.Email, 
      Ansatte.Mobilnr, 
      Login_data.Brugertype
   FROM 
      Ansatte 
         INNER JOIN Login_data 
            ON Ansatte.ansatID = Login_data.ansatID", con);

If you run the above query, it will return all records that are in the database that have a matching ID between each respective table.如果您运行上述查询,它将返回数据库中每个表之间具有匹配 ID 的所有记录。

Now, tack on parameters to a SQL-SELECT query.现在,将参数添加到 SQL-SELECT 查询。 Say you only wanted all names within a given PostNumber area.假设您只想要给定 PostNumber 区域内的所有名称。 Add a WHERE condition for such field and parameterized value such as为此类字段和参数化值添加 WHERE 条件,例如

   FROM 
      Ansatte 
         INNER JOIN Login_data 
            ON Ansatte.ansatID = Login_data.ansatID
   where
      Ansatte.Postnummer = @MyPostCriteria", con );
      

cmd.Parameters.Add("MyPostCriteria", SqlDbType.Int).Value = 11223;

Now, if you are trying to ADD a record TO the database, that would be an insert, and you can only do an insert into a single table at a time and might be something like below.现在,如果您尝试向数据库添加一条记录,那将是一次插入,并且您一次只能向单个表中插入一条记录,可能如下所示。 You identify the table and columns you want to insert, and then the values in the same sequence as their corresponding sequence as added in parenthesis list at the top.. Then parameterize您确定要插入的表和列,然后在顶部括号列表中添加与其对应序列相同序列的值。然后参数化

SqlCommand cmd = new SqlCommand(
@"INSERT INTO Ansatte
   ( Navn,
     Efternavn,
     Adresse
   )
   values
   ( @parmForNavn,
     @parmForEfternavn,
     @parmForAdresse
   )", con);


    cmd.Parameters.Add("parmForNavn", SqlDbType.VarChar).Value = "test";
    cmd.Parameters.Add("parmForEfternavn", SqlDbType.VarChar).Value = "blah";
    cmd.Parameters.Add("parmForAdresse", SqlDbType.VarChar).Value = "123 some street";

Hopefully this can jump-start you into what you are trying to accomplish from either pulling data down from a database, or insert into.希望这可以让您快速开始尝试通过从数据库中提取数据或插入数据来完成的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM