Read data from the student table and print it to the screen,Code
1 Class Program 2 { 3 Static Void Main ( String [] ARGs) 4 { 5 String Sqlc = @" Server =. \ sqlexpress; database = mydatabase15_31; uid = sa; Pwd = sa " ; 6 Using (Sqlconnection sqlconn = New Sqlconnection (sqlc )) 7 { 8 String SQL = @" Select * from student " ; 9 Using (Sqlcommand sqlcom = New Sqlcommand (SQL )) 10 { 11 If (Sqlconn. State = connectionstate. Closed) // Connectionstate enumeration describes the current status of the connection to the data source. 12 { // State indicates the status of sqlconnection. 13 14 Sqlconn. open (); 15 // Console. writeline ("succeeded "); 16 } 17 Sqldatareader reader = sqlcom. executereader (); // To create a sqldatareader, you must call the executereader method of the sqlcommand object instead of using the constructor directly. 18 Using (Reader) 19 { 20 If (Reader. hasrows) 21 { 22 // If (reader. Read ()) 23 While (Reader. Read ()) 24 { 25 Console. writeline (" {0} {1} {2} {3} {4} " , 26 Reader [ " Sid " ], 27 Reader [ " Sname " ], 28 Reader [" Sage " ], 29 Reader [ " Sgender " ], 30 Reader [ " Sclass " ] 31 ); 32 } 33 34 } 35 } 36 } 37 38 } 39 40 } 41 }
F6 is generated successfully. F5 reports an exception: executereader: Connection property has not been initialized.
Problem Analysis: When you see the connection, think of the database connection failure, through // console. writeline ("succeeded"); Eliminate the error, carefully verify the SQL statement, no problem, Baidu once said that the datareader function is called multiple times in the code, probably because too many links are opened, however, no problem was found after the check, and the problem suddenly occurred:
Using (sqlcommand sqlcom = new sqlcommand (SQL ))
The sqlcommand () parameter is missing. After correction
Using (sqlcommand sqlcom = new sqlcommand (SQL, sqlconn ))
Successfully passed.