1、注册MySQL Connector代码
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; // 注意, 不需要import com.mysql.jdbc.* // 否则会有问题 public class LoadDriver { public static void main(String[] args) { try { // The newInstance() call is a work around for some // broken Java implementations Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { // handle the error } } }
2、获取特定数据库连接
在驱动程序注册后 DriverManager,您可以Connection通过调用DriverManager.getConnection()以下命令获取连接到特定数据库的实例:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; Connection conn = null; ... try { conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=minty&password=greatsqldb"); // Do something with the Connection ... } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); }
官方文档:https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-connect-drivermanager.html