- Building Web Apps with Spring 5 and Angular
- Ajitesh Shukla
- 279字
- 2021-07-02 19:38:24
Connecting to the MySQL database from a Java class
In this section, you will learn how to test the MySQL database connection from a Java program. Note that this section is intended only to help you test the database connection from the Java class. In reality, we will use Springboot DataSourceBuilder to create a datasource bean, which will be used for connecting with the database.
Before executing the code shown as follows in your Eclipse IDE, make sure to do the following:
- Add the MySQL connector JAR file by right-clicking on the top-level project folder, clicking on Properties, clicking on Java Build Path, and then, adding the mysql-connector-java-xxx.jar file by clicking on Add External JARs...:

Figure 1.10: Adding MySQL Java Connector to Java Build Path in Eclipse IDE
- Create a MySQL database, namely, healthapp. You can do that by accessing MySQL Workbench, and executing the MySQL command create database healthapp. The following screenshot represents the same:

Figure 1.11: Creating new MySQL Database using MySQL Workbench
- Once done with the preceding steps, use the following code to test the connection to the MySQL database from your Java class. On successful connection, you should be able to see Database connected! be printed:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Sample program to test MySQL database connection */ public class App { public static void main( String[] args ) { String url =
"jdbc:mysql://localhost:3306/healthapp"; String username = "root"; String password = "r00t"; //Root password set
during MySQL installation procedure as
described above. 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); } } }
推薦閱讀
- INSTANT Mercurial SCM Essentials How-to
- 自制編程語(yǔ)言
- H5頁(yè)面設(shè)計(jì):Mugeda版(微課版)
- Hands-On Kubernetes on Windows
- 超好玩的Scratch 3.5少兒編程
- Hack與HHVM權(quán)威指南
- R語(yǔ)言實(shí)戰(zhàn)(第2版)
- HTML5 Game Development by Example:Beginner's Guide(Second Edition)
- Mastering Node.js
- Swift iOS Programming for Kids
- Node.js進(jìn)階之路
- BackTrack 5 Cookbook
- JavaWeb入門(mén)經(jīng)典
- 嵌入式Linux與物聯(lián)網(wǎng)軟件開(kāi)發(fā):C語(yǔ)言?xún)?nèi)核深度解析
- 亮劍C#項(xiàng)目開(kāi)發(fā)案例導(dǎo)航