Connect to a database

From CodeCodex




 $resource = db_connect($host, $user, $password) or die(mysql_error());
 // if mysql doesn't connect, it will stop the script and echo the error



This class loads a database connection, accepts SQL queries, and returns result sets. Before connecting to the database, you must download a JDBC driver. For MySQL use this driver.

import java.sql.*;

 * This class encapsulates a JDBC database connection and returns a ResultSetTableModel 
 * object suitable for display given a SQL query as a strin
public class DatabaseConnection {
    Connection connection;  // Holds the connection to the database

    /** Instantiate a db Connection 
     * @param driverClassName The name of the database driver class.  com.mysql.jdbc.Driver for MySQL
     * @param dbURL The database to connect to.  For MySQL: jdbc:mysql://host_name:port/dbname
     * @param userName The user name.
     * @param password The password.
     * @throws ClassNotFoundException
     * @throws SQLException
    public DatabaseConnection(String driverClassName, String dbURL, String userName, String password)
        throws ClassNotFoundException, SQLException
	// Look up the JDBC driver by class name.  When the class loads, it
	// automatically registers itself with the DriverManager used in
	// the next step.
	Class driver = Class.forName(driverClassName);

	// Now use that driver to connect to the database
	connection = DriverManager.getConnection(dbURL, userName, password);

     * This method takes a SQL query, passes it to the database, obtains the
     * results as a ResultSet, and returns a ResultSetTableModel object that
     * holds the results in a form that the Swing JTable component can use.
    public ResultSet getResultSet(String query)
        throws SQLException
		// If we've called close(), then we can't call this method
		if (connection == null)
		    throw new IllegalStateException("Connection already closed.");
		// Create a Statement object that will be used to excecute the query.
		// The arguments specify that the returned ResultSet will be 
		// scrollable, read-only, and insensitive to changes in the db.
		Statement statement =
		// Run the query, creating a ResultSet
		return statement.executeQuery(query);

     * Call this method when done with the factory to close the DB connection 
    public void close() {
		try { connection.close(); } // Try to close the connection
		catch (Exception e) {}      // Do nothing on error. At least we tried.
		connection = null; 

    /** Automatically close the connection when we're garbage collected */
    protected void finalize() { close(); }