Reading values from SQL database in C#

2019-01-17 15:22发布

问题:

i have just started learning C# and i can write data to the database without a problem. But i'm having problems with reading, the SQL executes fine but i'm having issues with storing it. How would i store the four columns that should be returned and then show them as a message box? Thanks.

SqlCommand myCommand = new SqlCommand("select * from Requests where Complete = 0", myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())

Console.WriteLine(myReader["Username"].ToString());
Console.WriteLine(myReader["Item"].ToString());
Console.WriteLine(myReader["Amount"].ToString());
Console.WriteLine(myReader["Complete"].ToString());

回答1:

One problem is missing braces after the while

while (myReader.Read())
{  // <<- here
    Console.WriteLine(myReader["Username"].ToString());
    Console.WriteLine(myReader["Item"].ToString());
    Console.WriteLine(myReader["Amount"].ToString());
    Console.WriteLine(myReader["Complete"].ToString());
}  // <<- here

if you skip the braces only the first line will be processed in each loop, the rest will be processed after the loop, then myReader is past the last row.



回答2:

Don't forget to use the using(){} block :

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("select * from Requests where Complete = 0", connection))
{
    connection.Open();  
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.WriteLine(reader["Username"].ToString());
            Console.WriteLine(reader["Item"].ToString());
            Console.WriteLine(reader["Amount"].ToString());
            Console.WriteLine(reader["Complete"].ToString());
        }
    }
}


回答3:

Personally I'd write a class with 4 properties (with matching names and types), then use "dapper" (http://code.google.com/p/dapper-dot-net/):

var data = connection.Query<Request>(
    "select * from Requests where Complete = 0").ToList();

With something like:

public class Request {
    public string Username{get;set;}
    ...
    public bool Complete {get;set;}
}

Dapper is free, simple, has parameterisation to avoid SQL-injection, and is very very fast.



回答4:

I would create an object with properties that holds those values and then pass that object around as needed.

public class YourObjectName
{
   public string Username { get; set; }
   public string Item { get; set; }
   public string Amount { get; set; }
   public string Complete { get; set; }
}

YourObjectName a = new YourObjectName();
a.Username = Reader['Username'].ToString();


回答5:

i know its a bit late but you can use local string variables,or string array or list insert the data in the database there and then call it in your console write line