Home > Java > Connect Java to MySQL database

Connect Java to MySQL database

王林
Release: 2024-02-22 12:58:14
forward
1106 people have browsed it

php editor Banana brings you a special question and answer about connecting Java to a MySQL database. This article will explain to you how to connect to a MySQL database in a Java application, allowing you to easily master relevant knowledge and improve your programming skills. Whether you are a beginner or an experienced developer, you can find a solution that suits you in this article to make database operations more efficient and convenient. Let’s dive in!

Question content

How to connect to mysql database using 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)
Copy after login

or

java.lang.classnotfoundexception: com.mysql.jdbc.driver
Copy after login

or

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Copy after login

Solution

Data source

drivermanager is a pretty old way of doing things. A better approach is to get the DataSource object. You can use JNDI to find the application server container that has been configured for you:

context context = new initialcontext();
datasource datasource = (datasource) context.lookup("java:comp/env/jdbc/mydb");
Copy after login

...or instantiate and configure one directly from the database driver, such as com.mysql.cj.jdbc.mysqldatasource (see documentation):

mysqldatasource datasource = new mysqldatasource();
datasource.setuser("scott");
datasource.setpassword("tiger");
datasource.setservername("mydbhost.example.org");
Copy after login

...and then get the connection 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();
Copy after login

In modern java, use the try-with-resources syntax to automatically close jdbc resources (now AutoCloseable).

try (
    connection conn = datasource.getconnection();
    statement stmt = conn.createstatement();
    resultset rs = stmt.executequery("select id from users");
) {
    …
}
Copy after login

Here are step-by-step instructions on how to install mysql and jdbc and how to use it:

  1. Download and install mysql server. Just do it the usual way. Remember it whenever you change the port number. Default is 3306.

  2. Download jdbc driver and put it in the classpath , unzip the zip file and put the included jar file in the classpath. Vendor-specific jdbc drivers are concrete implementations of the JDBC API (tutorial here).

    If you are using an IDE such as eclipse or netbeans, you can add the jar file to the classpath by adding it as a library to the Build Path property .

    If you do this in the "normal" way in the command console, you need to specify the jar file in the -cp or -classpath parameter when executing the java application path.

    java -cp .;/path/to/mysql-connector.jar com.example.yourclass
    Copy after login

    . just adds the current directory to the classpath so it can find com.example.yourclass and ; is the classpath separator because It's in the window. On unix and clones, : should be used.

    If you are developing a servlet-based war application and want to manage the connections manually (actually, this is a bad practice), then you need to ensure that the jar ends up in the built /web-inf/lib middle. See also How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib. A better approach is to install the physical jdbc driver jar file in the server itself and configure the server to create a jdbc connection pool. Here is an example for tomcat:How should I connect to JDBC database / datasource in a servlet based application?

  3. Create database in mysql. Let's create a database javabase. Of course you want to rule the world, so we use utf-8 as well.

    create database javabase default character set utf8 collate utf8_unicode_ci;
    Copy after login
  4. java accesses Create a user, which accesses grant. Simply because using root is a bad practice.

    create user 'java'@'localhost' identified by 'password';
     grant all on javabase.* to 'java'@'localhost' identified by 'password';
    Copy after login

    Yes, here java is the username and password is the password.

  5. Determine jdbc url. To connect to a mysql database using java, you need a jdbc url with the following syntax:

    jdbc:mysql://hostname:port/databasename
    Copy after login
    • hostname:安装 mysql 服务器的主机名。如果它安装在运行 java 代码的同一台机器上,那么您可以只使用 localhost。它也可以是 ip 地址,例如 127.0.0.1。如果您遇到连接问题,并且使用 127.0.0.1 而不是 localhost 解决了该问题,那么您的网络/dns/主机配置有问题。

    • port:mysql 服务器监听的 tcp/ip 端口。默认情况下为 3306

    • databasename:您要连接的数据库的名称。那是 javabase

    所以最终的 url 应如下所示:

    jdbc:mysql://localhost:3306/javabase
    Copy after login
  6. Test the connection 使用 java 到 mysql。使用 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);
     }
    
    Copy after login

    如果您收到 sqlexception: no合适的驱动程序,则意味着 jdbc 驱动程序根本没有自动加载,或者 jdbc url 错误(即,任何加载的驱动程序都无法识别它)。另请参见 The infamous java.sql.SQLException: No suitable driver found。通常,当您将 jdbc 4.0 驱动程序放入运行时类路径中时,应该会自动加载它。要排除其中一个或另一个,您可以随时手动加载它,如下所示:

     System.out.println("Loading driver ...");
    
     try {
         Class.forName("com.mysql.cj.jdbc.Driver"); // Use com.mysql.jdbc.Driver if you're not on MySQL 8+ yet.
         System.out.println("Driver loaded!");
     } catch (ClassNotFoundException e) {
         throw new IllegalStateException("Cannot find the driver in the classpath!", e);
     }
    
    Copy after login

    请注意,此处不需要调用 newinstance() 。对于mysql,只是为了修复旧的且有缺陷的org.gjt.mm.mysql.driverExplanation here。如果此行抛出 classnotfoundexception,则说明包含 jdbc 驱动程序类的 jar 文件根本没有放置在类路径中。另请注意,抛出异常非常重要,以便立即阻止代码执行,而不是仅仅打印堆栈跟踪然后继续执行其余代码来抑制它。

    另请注意,您不需要每次在连接之前加载驱动程序。只需在应用程序启动期间一次就足够了。

    如果您收到 sqlexception: 连接被拒绝 connection timed out 或 mysql 特定的 communicationsexception: 通信链路故障 ,则意味着数据库根本无法访问。这可能由以下一个或多个原因造成:

    1. jdbc url 中的 ip 地址或主机名错误。
    2. 本地 dns 服务器无法识别 jdbc url 中的主机名。
    3. jdbc url 中的端口号缺失或错误。
    4. 数据库服务器已关闭。
    5. 数据库服务器不接受 tcp/ip 连接。
    6. 数据库服务器已耗尽连接。
    7. java 和 db 之间的某些东西正在阻塞连接,例如防火墙或代理。

    要解决其中一个问题,请遵循以下建议:

    1. 使用 ping 验证并测试它们。
    2. 刷新 dns 或在 jdbc url 中使用 ip 地址。
    3. 根据mysql db的my.cnf进行验证。
    4. 启动数据库。
    5. 验证 mysqld 是否在没有 --skip-networking 选项 的情况下启动。
    6. 重新启动数据库并相应地修复代码,使其关闭 finally 中的连接。
    7. 禁用防火墙和/或配置防火墙/代理以允许/转发端口。

    请注意,关闭 connection 极其非常重要。如果您不关闭连接并在短时间内不断获取大量连接,那么数据库可能会耗尽连接,并且您的应用程序可能会崩溃。始终获取 try-with-resources statement 中的 connection。这也适用于 statementpreparedstatementresultset。另见How often should Connection, Statement and ResultSet be closed in JDBC?

    这就是连接问题。您可以在 here 找到更高级的教程,了解如何借助基本 dao 类在数据库中加载和存储完整的 java 模型对象。

    对数据库 connection 使用单例模式和/或 static 变量是一种不好的做法。参见其他 Is it safe to use a static java.sql.Connection instance in a multithreaded system? 这是第一个初学者错误。确保您不会落入这个陷阱。

    The above is the detailed content of Connect Java to MySQL database. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template