import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectToDataBase { public static Connection getDataBaseConnection(){ String driver="com.mysql.jdbc.Driver"; String url="jdbc:mysql://localhost:3306/db_pms"; String user="root"; String password="123456"; //加載驅動程序 try { Class.forName(driver); //URL:http://www.bianceng.cn/Programming/Java/201608/50376.htm //System.out.println("驅動程序加載成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } //鏈接數據庫 Connection conn=null; try { conn=DriverManager.getConnection(url, user, password); if (!conn.isClosed()) { System.out.println("連接數據庫成功"); } } catch (SQLException e) { System.out.println("鏈接數據庫失敗: "+e.getMessage()); } return conn; } }
Connection conn=ConnectToDataBase.getDataBaseConnection();