1 Importjava.sql.Connection;2 Importjava.sql.SQLException;3 Importjava.sql.Statement;4 ImportJava.sql.DriverManager;5 ImportJava.sql.ResultSet;6 7 8 Public classJavaE2 {9 Public Static voidMain (string[] args) {Ten Connection Conn; One Statement stmt; A ResultSet rs; -String url = "Jdbc:sqlserver://localhost:1433;databasename=test;"; -String sql = "SELECT * FROM Student"; the - - Try { -Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); + -}Catch(Exception ex) { +SYSTEM.OUT.PRINTLN ("Database load Failed"); A } at - - Try { - //connecting to a database -conn = drivermanager.getconnection (URL, "sa", "sa"); - //Creating statement Objects instmt =conn.createstatement (); - /** to * Statement createstatement () creates a Statement object to send SQL statements to the database. + */ - //Executing database query statements thers =stmt.executequery (SQL); * /** $ * ResultSet executeQuery (String sql) throws SQLException executes the given SQLPanax Notoginseng * statement, which returns a single ResultSet object - */ the while(Rs.next ()) { + intid = rs.getint ("SID"); AString name = rs.getstring ("SNAME"); the intAge = Rs.getint ("SSEX"); +System.out.println ("Sno:" + ID + "\tsame:" + name + "\tsage:" +Age ); - } $ if(rs! =NULL) { $ rs.close (); -rs =NULL; - } the if(stmt! =NULL) { - stmt.close ();Wuyistmt =NULL; the } - if(Conn! =NULL) { Wu conn.close (); -conn =NULL; About } $}Catch(SQLException e) { - e.printstacktrace (); -SYSTEM.OUT.PRINTLN ("Database connection Failed"); - } A } +}
Java SQL Server database connection succeeded