将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.DriverOr
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();更多推荐
发布评论