您如何连接到Java中的MySQL数据库?
当我尝试时,我得到
java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table at java.sql.DriverManager.getConnection(DriverManager.java:689) at java.sql.DriverManager.getConnection(DriverManager.java:247)
要么
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
DriverManager是一种相当古老的做事方式。更好的方法是DataSource通过查找已经为您配置的应用服务器容器来获取一个:
DriverManager
DataSource
Context context = new InitialContext(); DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
或直接从数据库驱动程序实例化和配置一个:
MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUser("scott"); dataSource.setPassword("tiger"); dataSource.setServerName("myDBHost.example.org");
然后从中获取连接,如上:
Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS"); ... rs.close(); stmt.close(); conn.close();