将Java连接到MySQL数据库

本文翻译自:Connect Java to a MySQL database

How do you connect to a MySQL database in Java? 您如何连接到Java中的MySQL数据库?

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

#1楼

参考:https://stackoom.com/question/BudV/将Java连接到MySQL数据库


#2楼

you need to have mysql connector jar in your classpath. 您需要在类路径中具有mysql连接器jar。

in Java JDBC API makes everything with databases. Java JDBC API中的所有功能都可以使用数据库。 using JDBC we can write Java applications to 使用JDBC,我们可以将Java应用程序编写为
1. Send queries or update SQL to DB(any relational Database) 2. Retrieve and process the results from DB 1.向数据库(任何关系数据库)发送查询或更新SQL。2.从数据库检索并处理结果

with below three steps we can able to retrieve data from any Database 通过以下三个步骤,我们可以从任何数据库中检索数据

Connection con = DriverManager.getConnection(
                     "jdbc:myDriver:DatabaseName",
                     dBuserName,
                     dBuserPassword);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");

while (rs.next()) {
    int x = rs.getInt("a");
    String s = rs.getString("b");
    float f = rs.getFloat("c");
}

#3楼

String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
String user = "username";
String password = "password";

// Load the Connector/J driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Establish connection to MySQL
Connection conn = DriverManager.getConnection(url, user, password);

#4楼

Here's the very minimum you need to get data out of a MySQL database: 这是从MySQL数据库中获取数据的最低要求:

Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection
   ("jdbc:mysql://localhost:3306/foo", "root", "password");

Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM `FOO.BAR`");
stmt.close();
conn.close();

Add exception handling, configuration etc. to taste. 添加异常处理,配置等。


#5楼

DriverManager is a fairly old way of doing things. DriverManager是一种相当古老的做事方式。 The better way is to get a DataSource , either by looking one up that your app server container already configured for you: 更好的方法是通过查找已经为您配置的应用服务器容器之一来获取DataSource

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

#6楼

Here's a step by step explanation how to install MySQL and JDBC and how to use it: 这是逐步说明如何安装MySQL和JDBC以及如何使用它:

  1. Download and install the MySQL server . 下载并安装MySQL服务器 Just do it the usual way. 只需按照通常的方式进行即可。 Remember the port number whenever you've changed it. 每次更改时都请记住端口号。 It's by default 3306 . 默认为3306

  2. Download the JDBC driver and put in classpath , extract the ZIP file and put the containing JAR file in the classpath. 下载 JDBC驱动程序并放入classpath ,解压缩ZIP文件并将包含的JAR文件放入classpath。 The vendor-specific JDBC driver is a concrete implementation of the JDBC API ( tutorial here ). 特定于供应商的JDBC驱动程序是JDBC API的具体实现( 此处提供了教程 )。

    If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties. 如果使用的是Eclipse或Netbeans之类的IDE,则可以通过将JAR文件作为添加到项目属性中的“ 构建路径” ,将其添加到类路径中。

    If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application. 如果在命令控制台中执行“普通香草”操作,则在执行Java应用程序时需要在-cp-classpath参数中指定JAR文件的路径。

     java -cp .;/path/to/mysql-connector.jar com.example.YourClass java -cp。; / path / to / mysql-connector.jar com.example.YourClass 

    The . . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; 只是将当前目录也添加到类路径中,以便可以找到com.example.YourClass; is the classpath separator as it is in Windows. 是Windows中的类路径分隔符。 In Unix and clones : should be used. 在Unix和clones中:应该使用。

  3. Create a database in MySQL . 在MySQL中创建一个数据库 Let's create a database javabase . 让我们创建一个数据库javabase You of course want World Domination, so let's use UTF-8 as well. 您当然想要世界统治,所以我们也要使用UTF-8。

     CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; 
  4. Create an user for Java and grant it access . 创建 Java 用户授予其访问权限 Simply because using root is a bad practice. 仅仅因为使用root是一种不好的做法。

     CREATE USER 'java'@'localhost' IDENTIFIED BY 'password'; GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password'; 

    Yes, java is the username and password is the password here. 是的, java是用户名, password是此处的密码。

  5. Determine the JDBC URL . 确定 JDBC URL To connect the MySQL database using Java you need an JDBC URL in the following syntax: 要使用Java连接MySQL数据库,您需要使用以下语法的JDBC URL:

     jdbc:mysql://hostname:port/databasename jdbc:mysql://主机名:端口/数据库名 
    • hostname : The hostname where MySQL server is installed. hostname :安装MySQL服务器的主机名。 If it's installed at the same machine where you run the Java code, then you can just use localhost . 如果将它安装在运行Java代码的同一台计算机上,则可以只使用localhost It can also be an IP address like 127.0.0.1 . 它也可以是IP地址,例如127.0.0.1 If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config. 如果遇到连接问题,并且使用127.0.0.1而不是localhost解决了此问题,则您的网络/ DNS /主机配置中存在问题。

    • port : The TCP/IP port where MySQL server listens on. port :MySQL服务器侦听的TCP / IP端口。 This is by default 3306 . 默认情况下为3306

    • databasename : The name of the database you'd like to connect to. databasename :您要连接的数据库的名称。 That's javabase . 那是javabase

    So the final URL should look like: 因此,最终网址应如下所示:

     jdbc:mysql://localhost:3306/javabase jdbc:mysql:// localhost:3306 / javabase 
  6. Test the connection to MySQL using Java . 使用Java 测试与 MySQL 的连接 Create a simple Java class with a main() method to test the connection. 使用main()方法创建一个简单的Java类来测试连接。

     String url = "jdbc:mysql://localhost:3306/javabase"; String username = "java"; String password = "password"; System.out.println("Connecting database..."); try (Connection connection = DriverManager.getConnection(url, username, password)) { System.out.println("Database connected!"); } catch (SQLException e) { throw new IllegalStateException("Cannot connect the database!", e); } 

    If you get a SQLException: No suitable driver , then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (ie it wasn't recognized by any of the loaded drivers). 如果得到SQLException: No suitable driver ,则意味着JDBC驱动程序根本没有自动加载,或者JDBC URL错误(即,任何已加载的驱动程序都无法识别)。 Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. 通常,只要将JDBC 4.0驱动程序放入运行时类路径中就应该自动加载它。 To exclude one and other, you can always manually load it as below: 要排除其中的一个,您始终可以按如下所示手动加载它:

     System.out.println("Loading driver..."); try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver loaded!"); } catch (ClassNotFoundException e) { throw new IllegalStateException("Cannot find the driver in the classpath!", e); } 

    Note that the newInstance() call is not needed here. 注意newInstance()这里不需要调用。 It's just to fix the old and buggy org.gjt.mm.mysql.Driver . 这只是为了修复老旧的org.gjt.mm.mysql.Driver Explanation here . 在这里解释 If this line throws ClassNotFoundException , then the JAR file containing the JDBC driver class is simply not been placed in the classpath. 如果此行引发ClassNotFoundException ,则根本不会将包含JDBC驱动程序类的JAR文件放置在类路径中。

    Note that you don't need to load the driver everytime before connecting. 请注意,您不需要连接 每次都加载驱动程序。 Just only once during application startup is enough. 在应用程序启动期间仅一次就足够了。

    If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException: Communications link failure , then it means that the DB isn't reachable at all. 如果收到SQLException: Connection refusedConnection timed out或者MySQL特定的CommunicationsException: Communications link failure ,则意味着根本无法访问该数据库。 This can have one or more of the following causes: 可能有以下一种或多种原因:

    1. IP address or hostname in JDBC URL is wrong. JDBC URL中的IP地址或主机名错误。
    2. Hostname in JDBC URL is not recognized by local DNS server. 本地DNS服务器无法识别JDBC URL中的主机名。
    3. Port number is missing or wrong in JDBC URL. JDBC URL中的端口号丢失或错误。
    4. DB server is down. 数据库服务器已关闭。
    5. DB server doesn't accept TCP/IP connections. DB服务器不接受TCP / IP连接。
    6. DB server has run out of connections. 数据库服务器已用尽连接。
    7. Something in between Java and DB is blocking connections, eg a firewall or proxy. Java和DB之间的某种事物正在阻止连接,例如防火墙或代理。

    To solve the one or the other, follow the following advices: 要解决一个或另一个,请遵循以下建议:

    1. Verify and test them with ping . 使用ping验证并测试它们。
    2. Refresh DNS or use IP address in JDBC URL instead. 刷新DNS或在JDBC URL中使用IP地址。
    3. Verify it based on my.cnf of MySQL DB. 根据MySQL DB的my.cnf进行验证。
    4. Start the DB. 启动数据库。
    5. Verify if mysqld is started without the --skip-networking option . 验证mysqld是否在没有--skip-networking option情况下启动。
    6. Restart the DB and fix your code accordingly that it closes connections in finally . 重新启动数据库并相应地修复代码,以finally关闭连接。
    7. Disable firewall and/or configure firewall/proxy to allow/forward the port. 禁用防火墙和/或配置防火墙/代理以允许/转发端口。

    Note that closing the Connection is extremely important. 请注意,关闭Connection 非常重要。 If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. 如果您不关闭连接并在短时间内保持大量连接,则数据库可能会用尽连接,并且您的应用程序可能会中断。 Always acquire the Connection in a try-with-resources statement . 始终在try-with-resources语句中获取Connection Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. 或者,如果您尚未使用Java 7,请在finallytry-finally块中明确关闭它。 Closing in finally is just to ensure that it get closed as well in case of an exception. finally关闭只是为了确保在发生异常时也能关闭它。 This also applies to Statement , PreparedStatement and ResultSet . 这也适用于StatementPreparedStatementResultSet

That was it as far the connectivity concerns. 就连接性而言,仅此而已。 You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class. 您可以在这里找到更高级的教程,该教程如何在基本DAO类的帮助下将有价值的Java模型对象加载和存储在数据库中。


Using a Singleton Pattern for the DB connection is a bad approach. 对数据库连接使用单例模式是一种不好的方法。 See among other questions: http://stackoverflow.com/q/9428573/ . 参见其他问题: http : //stackoverflow.com/q/9428573/ This is a #1 starters mistake. 这是#1入门错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值