complexconstructorexample.java

来自「这个虽然非常简单」· Java 代码 · 共 67 行

JAVA
67
字号
import java.sql.*;

public class ComplexConstructorExample
{

	// 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";

	public static void main(String[] args) 
	{
		ConnectionPool pool = null;
		try 
		{
			 // open a pool of 10 connections - when I run low, open 5 more
			 // check my pool's health every 2 minutes, and keep "extra" idle
			 // connections alive for 3 minutes before closing them down
			 pool = new ConnectionPool( dbURL , dbUserName , dbPassword, dbDriver, 10, 5, 2, 3 );	 
		} 
		catch(SQLException e)  // thrown if problems building connections to database
		{
			System.out.println( e.getMessage() );
		}
		catch(ClassNotFoundException cnf)  // thrown if db class driver not found in classpath
		{
			System.out.println( cnf.getMessage() );
		}

		// now that the pool is running, we can use it's connections...

		Connection con = null;
		try {
			con = pool.getConnection();    // get a connection from the pool
			// use the connection...
			// ...
			useConnection( con );
			// done using the connection
			pool.returnConnection( con );  // return the connection to the pool					 
		    System.out.println( pool.getReport() ); // let's see a report
		} 
		catch(SQLException e)  // thrown if problems building connections to database
		{
			System.out.println( e.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 + -
显示快捷键?