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 classAccesstest { 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 ("Sun.jdbc.odbc.JdbcOdbcDriver"); + A //establish database connection; atConnection Connection = drivermanager.getconnection ("Jdbc:odbc:Warrior"); - //Note: There are some solutions to errors when making an Access data source: - //1. Select an ODBC data source (32-bit) or an ODBC data source (64-bit) that must be consistent with the JDK (32 or 64-bit) version. - //2. When you use Office2007 or a later version of Access, you need to save the database as a Microsoft Access database (2002~2003 format). - //remember not to directly modify the file's extension to. mdb, otherwise it will report "Cannot open database" (unknown). The application may not recognize the - //the database, or the file may be corrupted. The application may not recognize the database, or the file may be corrupted. "Error. in - //create the SQL statement, execute the statement, return the result set; toStatement Statement =connection.createstatement (); +ResultSet ResultSet = Statement.executequery ("SELECT * from User"); - the //processing result sets (including metadata); * //Print property name; $ResultSetMetaData Rsmetadata =Resultset.getmetadata ();Panax Notoginseng for(inti = 1; I <= rsmetadata.getcolumncount (); i++) { -System.out.printf ("%-8s\t", Rsmetadata.getcolumnname (i)); the } + System.out.println (); A the //print attribute values; + while(Resultset.next ()) { - for(inti = 1; I <= rsmetadata.getcolumncount (); i++) { $System.out.printf ("%-12s\t", resultset.getstring (i)); $ } - System.out.println (); - } the - //close the database connection; (Connecting the database is a big overhead in Java applications.) )Wuyi connection.close (); the } - Wu}
JDBC Programming: Connecting to access detailed examples