针对不同查询的多个Sql命令c#

时间:2012-02-20 22:48:44

标签: c# sql

我对C#和SQL工作比较陌生,我目前有一个我正在处理的应用程序,它对一个表有一些查询,所有这些都在不同情况下使用,例如在特定事件更新时或者例如,选择此项以查看它是否与之匹配

我问的原因是有没有办法将这些查询组合在一起,因为它们都在查询同一个表格,或者它们最好分开?

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

非常感谢,

1 个答案:

答案 0 :(得分:2)

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

正如已经提到的,初学数据访问教程可能是很好的阅读。但是这里有一些快速而肮脏的信息可以让你在正确的方向上轻推。大多数这是你可以做到这一点的几种方式之一(你应该知道差异),是我通常喜欢的方式,或者我认为对于一个完整的新手来说是最容易理解的 - 在这之后看看几个教程!

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

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循环并通过用一个int变量替换Rows [0]来迭代遍历行。

我实际上并没有编译和测试上面的代码,但我相信它应该可行。如果没有,基本概念至少存在,我相信你可以运行并解决我可能遇到过的任何拼写错误;)

相关问题