一尘不染

将Java连接到MySQL数据库

mysql

您如何连接到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

阅读 323

收藏
2020-05-17

共1个答案

一尘不染

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();
2020-05-17