搜索并显示sql数据库数据C#

时间:2014-10-31 15:18:48

标签: c# sql-server

我是编码新手,目前正在使用sql数据库。我应该创建一个数据库,在控制台应用程序中显示数据库中的所有信息,然后搜索特定的" customerID" (数据库中的一列)并显示有关该客户的信息。

我已经能够创建数据库并显示信息,但我不确定如何在控制台应用程序中显示数据。我可以显示最上面的行信息,但我无法弄清楚如何到达较低的行。我从教导我的人那里获得的信息并没有给我足够的信息。

请帮忙!

SqlCeConnection con1 = new SqlCeConnection(conStr);
con1.Open();
SqlCeCommand cmd1 = new SqlCeCommand("SELECT * FROM shippingTable", con1);
SqlCeDataReader dr = cmd1.ExecuteReader();

Console.WriteLine("Enter your customer ID (C1, C2 or C3");
string userValue = Console.ReadLine();

while (dr.Read())
{

    if (userValue == "C1")
        {
            Console.WriteLine(dr[1] + "Your product was shipped: " + dr[5]);
            break;
        }

    if (userValue == "C2")
        {
            Console.WriteLine(dr[1] + "Your product was shipped: " + dr[5]);
            break;
        }
    if (userValue == "C3")
        {
            Console.WriteLine(dr[1] + "Your product was shipped: " + dr[5]);
            break;
        }
    else
        {
            Console.WriteLine("Something went wrong, you typed in the wrong customer ID");
            break;
        }
}

2 个答案:

答案 0 :(得分:1)

您应该使用sql查询中的where子句过滤数据库端的数据。

"SELECT * FROM shippingTable WHERE CustomerID = @CustomerID"

然后,当您设置命令时,您需要传入参数及其值:

cmd1.Parameters.Add("CustomerID", SqlDbType.VarChar).Value = userValue;

这意味着您不必编写代码来搜索代码中客户ID的可能值 - 因为如果有一百万客户,您会怎么做?

您可以使用"SELECT * FROM shippingTable WHERE CustomerID = '" + userValue + "'",但正如@AndyKorneyev在下面的评论中指出的那样,这将使您的代码对注入攻击开放。

同样地使用cmd1.Parameters.AddWithValue("CustomerID", userValue)会有效,但会遇到会影响应用程序性能的转换问题 - @AndyKorneyev也指出了与解释问题的文章的良好链接。

考虑更像这样的事情:

        Console.Write( "Enter your customer ID: " );
        string userValue = Console.ReadLine(); // Get this before you even try and make a connection.

        using( SqlConnection con1 = new SqlConnection( conStr ) ) // using is used here because these objects implement IDisposable
        {
            con1.Open(); // Using will take care of closing the connection when it leaves scope.
            using( SqlCommand cmd1 = new SqlCommand( "SELECT * FROM shippingTable WHERE CustomerId = @CustomerId", con1 ) )
            {
                cmd1.Parameters.Add("CustomerID", SqlDbType.VarChar).Value = userValue;
                using( SqlDataReader dr = cmd1.ExecuteReader() )
                {
                    if( dr.Read() )
                    {
                        Console.WriteLine( dr[ 1 ] + " Your product was shipped: " + dr[ 5 ] );
                    }
                    else
                    {
                        Console.WriteLine( "Nothing was returned for Customer Id '" + userValue + "'" );
                    }
                }
            }
        }

答案 1 :(得分:0)

将数据库中的数据读入控制台应用程序的方法是:

/* This approach will allow for parameters, avoiding Sql Injection.
   It also shows the 'TOP' for result, to limit the data your pulling.  The larger 
   the table, the slower the application. (Just example, tweak for real world.)
*/
string query = "SELECT TOP 50 * FROM [Database] WHERE ([Id] = @Id AND [Type] = @Type);";
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbInConfig"].ConnectionString))
     using(SqlCommand command = new SqlCommand(query, connection))
     {
          /*  The 'Using' will implement IDispose, which will save
              you resources, as once an item it out of scope will be 
              collected by Garbage Collection.
           */

           connection.Open(); // Self explanatory, open your database connection.

           // You can declare a parameter should you need one like this:
           command.Parameters.AddWithValue("@Id", id);

          /* The downfall with 'AddWithValue' is it attempts to infer
             the database type, which can be wrong. */

          command.Parameters.Add("@Id", SqlDbType.Int).Value = type;

          /* The generic add has you manually specifying the type,
             less room for error especially with big data.

          // Execute a Reader, to Read the data.
          using(SqlDataReader reader = command.ExecuteReader())
               while(reader.Read())
               {
                    // Within this scope, you can transmit data anyway you'd like.
                    if(reader["Column"] != DBNull.Value)
                         Console.WriteLine(reader["Column"].ToString());

                    /* You could populate a data model, or list to send 
                       to console in a tabular format.  Or do what I did
                       above which would show them one at a time. */
               }
     }

这应该让你开始使用数据库,希望也为你澄清一点。使用SqlDataReader从您的查询中读取数据。更多信息here