将Java连接到MySQL数据库 [英] Connect Java to a MySQL database
本文介绍了将Java连接到MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用Java连接到MySQL数据库?
How do you connect to a MySQL database in Java?
当我尝试时,我得到
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
,或者查看你的app服务器容器已经为你配置了一个:
DriverManager
is a fairly old way of doing things. The better way is to get a DataSource
, either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
或直接从数据库驱动程序中实例化和配置一个:
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");
然后从中获取连接,与上面相同:
and then obtain connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();
这篇关于将Java连接到MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文