import java.sql.*; /* A simple demo showing how to use JDBC and the jdbc driver to connect to a MySQL database and execute a query. The command line arguments are the user name, the password, the database name, and a query string enclosed in double quotes. The connection uses localhost and the default MySQL port 3306. */ public class MySQLTester { private String host = "localhost"; private String port = "3306"; public static void main(String[] args) { MySQLTester prog = new MySQLTester(); if (args.length == 4) { prog.run(args[0], args[1], args[2], args[3]); } else { System.out.println("Args: user password database \"query\""); } } public void run(String user, String password, String database, String query ) { try { // Load the driver class dynamically // This creates an instance of the class Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Could not find the MySQL driver"); System.exit(0); } try { // Create a connection using the mysql driver and return the // connection object Connection conn = DriverManager.getConnection( "jdbc:mysql://" + host + ":" + port + "/" + database + "?user=" + user + "&password=" + password); // Execute a query on the connection object using a Statement // object. The results are returned in the ResultSet object. Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); // table rows // The ResultSetMetaData object contains information about // the database table such as the column names and the number // of columns in the table. ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); // display column names (indices begin at 1) using the // colon as a field separator for (int i = 1; i <= numberOfColumns; i++) { System.out.print(rsmd.getColumnName(i)); if (i < numberOfColumns) System.out.print(":"); } System.out.println(); // Use the ResultSet iterator to iterate through each row // of the table and display the data for each row using the // colon as a field separator. while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { String columnValue = rs.getString(i); System.out.print(columnValue); if (i < numberOfColumns) System.out.print(":"); } System.out.println(); } rs.close(); conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); System.exit(0); } } }