simpleconstructorexample.java

来自「带有自我调整功能Connection Pool(JDBC」· Java 代码 · 共 55 行

JAVA
55
字号
import java.sql.*;

public class SimpleConstructorExample
{

	// if you have a database running, change these to work for your environment
	static String dbURL = "jdbc:mysql://localhost:3306/store_product";
	static String dbUserName = "";
	static String dbPassword = "";
	static String dbDriver = "org.gjt.mm.mysql.Driver";

	// show an example of using the simple constructor
    public static void main(String[] args) 
    {
        ConnectionPool pool = new ConnectionPool();  // start a default pool
        try
        {
            pool.setURL( dbURL );                                  // database url
            pool.setDriverClassName( dbDriver );                   // must be in classpath!
			pool.setUser( dbUserName );                            // set username
			pool.setPassword( dbPassword );                        // set password
            pool.start();                                          // Start the pool
            Connection con = pool.getConnection("Test Program");   // get a connection from the pool and identify ourselves         
			useConnection(con);			                           // here is where we use the pool
            pool.returnConnection( con );                          // return a connection to the pool
            System.out.println( pool.getReport() );                // let's see a report of the pool
        }
        catch(SQLException e)  // might be thrown by start() or getConnection()
        {
            System.out.println( e.getMessage() );
        }
        catch(ClassNotFoundException cnf)  // might be thrown by setDriverClassName()
        {
            System.out.println( cnf.getMessage() );
        }       
    }

    // simple example to use connection
	public static void useConnection(Connection con) throws SQLException
	{
		System.out.println("Just displaying the tables in the current database...");
		Statement statmt;
		ResultSet res;
		statmt = con.createStatement();
		String statement = "show tables"; // some dumb query that should work everywhere
		res = statmt.executeQuery(statement);
		while ( res.next() )
			System.out.println( res.getString(1) );

		res.close();
		statmt.close();
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?