我还没有努力使这项工作与 Hibernate 一起工作,但如果失败,您仍然可以使用良好的老式 JDBC 连接:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
static final String DB_ADDRESS = "localhost";
static final String DB_NAME = "mysql";
static final String DB_USER = "root";
public static void main (String[] args) {
// get password
String password = "";
if (args!=null && args.length>0) {
password = args[0];
}
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
System.out.println("Driver issue: " + ex.getMessage());
System.out.println("Driver issue: " + ex.getClass().toString());
}
// connect to database
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://"+DB_ADDRESS+"/"+DB_NAME+"?autoReconnect=true",DB_USER,password);
// Do something with the Connection
System.out.println("Connection: " + conn);
Statement stmt = conn.createStatement();
ResultSet RS = stmt.executeQuery("SHOW TABLES");
while (RS.next()) {
System.out.println("table: '" + RS.getString(1) + "'");
}
// disconnect from database
conn.close();
stmt.close();
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
}
这将返回:
Connection: com.mysql.jdbc.JDBC4Connection@528acf6e
table: 'columns_priv'
table: 'db'
table: 'event'
table: 'func'
table: 'general_log'
table: 'help_category'
table: 'help_keyword'
table: 'help_relation'
table: 'help_topic'
table: 'host'
table: 'ndb_binlog_index'
table: 'plugin'
table: 'proc'
table: 'procs_priv'
table: 'proxies_priv'
table: 'servers'
table: 'slow_log'
table: 'tables_priv'
table: 'time_zone'
table: 'time_zone_leap_second'
table: 'time_zone_name'
table: 'time_zone_transition'
table: 'time_zone_transition_type'
table: 'user'
不用说,关键是确保您的用户拥有足够的权限。