Table of Contents
Question content
Solution
Data source
Home Java Connect Java to MySQL database

Connect Java to MySQL database

Feb 22, 2024 pm 12:58 PM
java application overflow

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The price of Bitcoin since its birth 2009-2025 The most complete summary of BTC historical prices The price of Bitcoin since its birth 2009-2025 The most complete summary of BTC historical prices Jan 15, 2025 pm 08:11 PM

Since its inception in 2009, Bitcoin has become a leader in the cryptocurrency world and its price has experienced huge fluctuations. To provide a comprehensive historical overview, this article compiles Bitcoin price data from 2009 to 2025, covering major market events, changes in market sentiment, and important factors influencing price movements.

Overview of the historical price of Bitcoin since its birth. Complete collection of historical price trends of Bitcoin. Overview of the historical price of Bitcoin since its birth. Complete collection of historical price trends of Bitcoin. Jan 15, 2025 pm 08:14 PM

Bitcoin, as a cryptocurrency, has experienced significant market volatility since its inception. This article will provide an overview of the historical price of Bitcoin since its birth to help readers understand its price trends and key moments. By analyzing Bitcoin's historical price data, we can understand the market's assessment of its value, factors affecting its fluctuations, and provide a basis for future investment decisions.

A list of historical prices since the birth of Bitcoin BTC historical price trend chart (Latest summary) A list of historical prices since the birth of Bitcoin BTC historical price trend chart (Latest summary) Feb 11, 2025 pm 11:36 PM

Since its creation in 2009, Bitcoin’s price has experienced several major fluctuations, rising to $69,044.77 in November 2021 and falling to $3,191.22 in December 2018. As of December 2024, the latest price has exceeded $100,204.

The latest price of Bitcoin in 2018-2024 USD The latest price of Bitcoin in 2018-2024 USD Feb 15, 2025 pm 07:12 PM

Real-time Bitcoin USD Price Factors that affect Bitcoin price Indicators for predicting future Bitcoin prices Here are some key information about the price of Bitcoin in 2018-2024:

How to customize the resize symbol through CSS and make it uniform with the background color? How to customize the resize symbol through CSS and make it uniform with the background color? Apr 05, 2025 pm 02:30 PM

The method of customizing resize symbols in CSS is unified with background colors. In daily development, we often encounter situations where we need to customize user interface details, such as adjusting...

Is H5 page production a front-end development? Is H5 page production a front-end development? Apr 05, 2025 pm 11:42 PM

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

The text under Flex layout is omitted but the container is opened? How to solve it? The text under Flex layout is omitted but the container is opened? How to solve it? Apr 05, 2025 pm 11:00 PM

The problem of container opening due to excessive omission of text under Flex layout and solutions are used...

Why are the inline-block elements misaligned? How to solve this problem? Why are the inline-block elements misaligned? How to solve this problem? Apr 04, 2025 pm 10:39 PM

Regarding the reasons and solutions for misaligned display of inline-block elements. When writing web page layout, we often encounter some seemingly strange display problems. Compare...