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());
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.
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.
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.
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()); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With