1 PackageOrg.warnier.zhang.jdbc;2 3 Importjava.sql.Connection;4 ImportJava.sql.DriverManager;5 ImportJava.sql.ResultSet;6 ImportJava.sql.ResultSetMetaData;7 Importjava.sql.SQLException;8 Importjava.sql.Statement;9 Ten Public classMysqltest { One A /** - * @paramargs - * @throwsclassnotfoundexception the * @throwsSQLException - */ - Public Static voidMain (string[] args)throwsClassNotFoundException, - SQLException { + //load the driver; (The virtual machine loads the class, not the one that is used during programming.) ) -Class.forName ("Com.mysql.jdbc.Driver"); + A //establish database connection; atConnection Connection =DriverManager -. getconnection ("Jdbc:mysql://localhost/userinfo", "Warrior", "[email protected]"); - - //create the SQL statement, execute the statement, return the result set; -Statement Statement =connection.createstatement (); -ResultSet ResultSet = Statement.executequery ("SELECT * from User"); in - //processing result sets (including metadata); to //Print property name; +ResultSetMetaData Rsmetadata =Resultset.getmetadata (); - for(inti = 1; I <= rsmetadata.getcolumncount (); i++) { theSystem.out.printf ("%-8s\t", Rsmetadata.getcolumnname (i)); * } $ System.out.println ();Panax Notoginseng - //print attribute values; the while(Resultset.next ()) { + for(inti = 1; I <= rsmetadata.getcolumncount (); i++) { ASystem.out.printf ("%-12s\t", resultset.getstring (i)); the } + System.out.println (); - } $ $ //close the database connection; (Connecting the database is a big overhead in Java applications.) ) - connection.close (); - } the -}
JDBC Programming: Connection MySQL detailed example