Reading values from SQL database in C#

前端 未结 5 1021
陌清茗
陌清茗 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: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());
            }
        }
    }
    

提交回复
热议问题