Reading values from SQL database in C#

前端 未结 5 993
陌清茗
陌清茗 2020-12-14 01:45

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 w

相关标签:
5条回答
  • 2020-12-14 02:26

    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.

    0 讨论(0)
  • 2020-12-14 02:30

    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();
    
    0 讨论(0)
  • 2020-12-14 02:30

    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

    0 讨论(0)
  • 2020-12-14 02:32

    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.

    0 讨论(0)
  • 2020-12-14 02:34

    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());
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题