MySQL Connector/J JDBC驱动程序的1个特点是,能够在JDBC连接字符串中将“SocketFactory”指定为参数。MySQL Connector/MXJ包含1个定制的SocketFactory。首次连接时,SocketFactory将部署并启动MySQL数据库。SocketFactory也会显示1个“shutdown”方法。
要想使用它,请在JDBC连接字符串上指定“socketFactory”参数,并将其值设为“com.mysql.management.driverlaunched.ServerLauncherSocketFactory”。
在下面的示例中,有1个能创建连接的程序,执行查询,并将结果输出到System.out。MySQL数据库将作为连接进程的组成部分予以部署并启动,最后是结束部分。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import com.mysql.management.driverlaunched.ServerLauncherSocketFactory; public class ConnectorMXJTestExample { public static void main(String[] args) throws Exception { String hostColonPort = "localhost:3336"; String driver = com.mysql.jdbc.Driver.class.getName(); String url = "jdbc:mysql://" + hostColonPort + "/" + "?" + "socketFactory=" + ServerLauncherSocketFactory.class.getName(); String userName = "root"; String password = ""; Class.forName(driver); Connection conn = null; try { conn = DriverManager.getConnection(url, userName, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT VERSION()"); rs.next(); String version = rs.getString(1); rs.close(); stmt.close(); System.out.println("------------------------"); System.out.println(version); System.out.println("------------------------"); } finally { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } ServerLauncherSocketFactory.shutdown(hostColonPort); } } }
要想运行上述程序,在CLASSPATH中必须有connector-mxj.jar和Connector/J。然后键入:
java ConnectorMXJTestExample
当然,对于MySQL数据库,有很多可设置的选项。通过为每个服务器选项冠以前缀“server”,可将其作为JDBC连接字符串的部分,简单地指定这些选项。在下述示例中,我们设置了3个驱动程序参数和2个服务器参数:
String url = "jdbc:mysql://" + hostColonPort + "/" + "?" + "socketFactory=" + ServerLauncherSocketFactory.class.getName(); + "&" + "cacheServerConfiguration=true" + "&" + "useLocalSessionState=true" + "&" + "server.basedir=/opt/myapp/db" + "&" + "server.datadir=/mnt/bigdisk/myapp/data";