A feature of the MySQL Connector/J JDBC driver is the ability to specify a connection to an embedded Connector/MXJ instance through the use of the mxj keyword in the JDBC connection string.
In the following example, we have a program which creates a connection, executes a query, and prints the result to the System.out. The MySQL database will be deployed and started as part of the connection process, and shutdown as part of the finally block.
You can find this file in the Connector/MXJ package as
src/ConnectorMXJUrlTestExample.java
.
import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import com.mysql.management.driverlaunched.ServerLauncherSocketFactory; public class ConnectorMXJUrlTestExample { public static String DRIVER = "com.mysql.jdbc.Driver"; public static String JAVA_IO_TMPDIR = "java.io.tmpdir"; public static void main(String[] args) throws Exception { File ourAppDir = new File(System.getProperty(JAVA_IO_TMPDIR)); File databaseDir = new File(ourAppDir, "test-mxj"); int port = 3336; String url = "jdbc:mysql:mxj://localhost:" + port + "/test" + "?" + "server.basedir=" + databaseDir; System.out.println(url); String userName = "root"; String password = ""; Class.forName(DRIVER); Connection conn = null; try { conn = DriverManager.getConnection(url, userName, password); printQueryResults(conn, "SELECT VERSION()"); } finally { try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } ServerLauncherSocketFactory.shutdown(databaseDir, null); } } public static void printQueryResults(Connection conn, String SQLquery) throws Exception { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(SQLquery); int columns = rs.getMetaData().getColumnCount(); System.out.println("------------------------"); System.out.println(); while (rs.next()) { for (int i = 1; i <= columns; i++) { System.out.println(rs.getString(i)); } System.out.println(); } rs.close(); stmt.close(); System.out.println("------------------------"); System.out.flush(); Thread.sleep(100); // wait for System.out to finish flush } }
To run the above program, be sure to have connector-mxj.jar and Connector/J in the CLASSPATH. Then type:
java ConnectorMXJTestExample
Ésta es una traducción del manual de referencia de MySQL, que puede encontrarse en dev.mysql.com. El manual de referencia original de MySQL está escrito en inglés, y esta traducción no necesariamente está tan actualizada como la versión original. Para cualquier sugerencia sobre la traducción y para señalar errores de cualquier tipo, no dude en dirigirse a mysql-es@vespito.com.