用于不同查询的多个Sql命令c#

本文关键字:Sql 命令 查询 用于 | 更新日期: 2023-09-27 18:25:25

我对C#和SQL工作相对陌生,我目前正在开发一个应用程序,该应用程序对一个表有几个查询,所有这些查询都在不同的情况下使用,例如在特定事件中更新this或选择this以查看它是否匹配etc

然而,我问的原因是,有没有一种方法可以将这些查询组合起来,因为它们都查询同一个表,还是最好将它们分开?

另一件让我困惑的事情是,如何在选择查询中获得特定列的特定值?我不太确定如何使用C#代码访问它,任何简单的例子都非常感谢。

非常感谢,

用于不同查询的多个Sql命令c#

如果我理解正确的话,您有一个查询,您在代码中的几个不同位置使用它-每次访问相同的信息,只是在不同的情况下?你不确定如何获得你想要的特定列数据?

如前所述,初学者的数据访问教程可能是一本不错的读物。但这里有一些快速而肮脏的信息可以让你朝着正确的方向前进。其中大部分是我通常喜欢的几种方法之一(你应该知道其中的区别),或者我只是认为这对一个完全的新手来说是最容易理解的——之后一定要看几个教程!

首先,如果您反复使用同一个查询,如果有几个参数传递给SQL,我更喜欢将其放入存储过程中。您应该使用参数,总是(请参阅示例),以避免数据注入和类型转换问题。我刚开始的时候并不知道这一点,因此养成了不使用参数的坏习惯——这很难打破。。。所以现在就开始吧!最终,您将从数据库中取回数据集。。。该集合可以表示从一列数据到整个数据库的任何数据,因此您必须导航该结果数据集,才能在每个特定情况下找到您真正想要的结果(就像用一个值填充一个文本框,用另一个值填满另一个文本盒……这两个值都在相同的数据集中,不需要为每个文本框查询数据库,只需高效地查询一次,您就应该拥有所需的值。)

Animals_Table:

AnimalID, Name  , Type
1       , Frog  , Amphibian
2       , Snake , Reptile
3       , Bear  , Mammal
3       , Lion  , Mammal

在C#中:

        SqlCommand myCommand = new SqlCommand(); //The command you intend to pass to SQL
        DataSet myDataSet = new DataSet(); //The Dataset you'll fill and retrieve info from
        SqlConnection myConnection = new SqlConnection(Properties.Settings.Default.yourConnectionString); // I prefer my connection string to be in my project's properties. Don't put sensitive info like passwords here though

        myCommand.CommandType = CommandType.Text; // In this case we're using a text command, not stored procedure.  That means you're typing out your command, as a string, in c# (next line)
        myCommand.CommandText = "SELECT * FROM Animals_Table WHERE Type=@Type"; // @ denotes a parameter, in this case named Type
        myCommand.Parameters.AddWithValue("Type", "Mammal"); //You can also do Add instead of AddWithValue - this lets/forces you to input the type information manually.  It's more of a pain, but can resolve problems if c# doesn't make right assumptions
        myConnection.Open();  // Open your connection
        Command.Connection = myConnection;  // Plug that connection into your command
        SqlDataAdapter adapter = new SqlDataAdapter(Command); // Plug that command into a data adapter
        adapter.Fill(myDataSet); // populate your DataSet
        // Now you can use the data you've retrieved (your DataSet)
        textboxReturnedAnimalName1.Text = myDataSet.Tables[0].Rows[0]["Name"]; //You want the Name field from SQL, for the first table returned, and the first row in that table

由于您检索的数据集可能有多个表,每个表都有多行,因此您必须指定要访问的表(通常是第一个/唯一的表,对于这个简单的示例,是第一行。您还可以创建for循环,并通过将rows[0]替换为递增每个循环的int变量来迭代行。

我还没有真正编译和测试上面的代码,但我相信它应该可以工作。如果没有,至少基本概念已经存在,我相信你可以用它来解决我可能出现的任何拼写错误;)