将Java连接到MySQL数据库(Connect Java to a MySQL database)

编程入门 行业动态 更新时间:2024-10-25 13:16:52
将Java连接到MySQL数据库(Connect Java to a MySQL database)

如何使用Java连接到MySQL数据库?

How do you connect to a MySQL database in Java?

When I try, I get

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)

Or

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Or

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

最满意答案

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();

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();

更多推荐

本文发布于:2023-08-03 14:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接到   数据库   Java   MySQL   database

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!