Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading values from SQL database in C#

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()); 
like image 500
Paul Avatar asked May 14 '11 17:05

Paul


People also ask

Can we use SQL with C?

You can code SQL statements in a C or C++ program wherever you can use executable statements. Each SQL statement in a C or C++ program must begin with EXEC SQL and end with a semicolon (;). The EXEC and SQL keywords must appear on one line, but the remainder of the statement can appear on subsequent lines.

Can we connect database with C?

You can then add a new C source file and replace it with this content. Using the ODBC APIs SQLAllocHandle, SQLSetConnectAttr, and SQLDriverConnect, you should be able to initialize and establish a connection to your database.


2 Answers

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.

like image 67
Albin Sunnanbo Avatar answered Sep 30 '22 23:09

Albin Sunnanbo


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());         }     } } 
like image 43
abatishchev Avatar answered Sep 30 '22 23:09

abatishchev