Home Java Javagetting Started How many ways does java have to connect to mysql? What are the differences?

How many ways does java have to connect to mysql? What are the differences?

Nov 23, 2020 pm 03:33 PM
java mysql

How many ways does java have to connect to mysql? What are the differences?

There are five ways to connect java to mysql, which are:

(Learning video sharing: java teaching video)

The first way: encapsulate the username and password in the Properties class

First of all, there is no doubt about importing the database connection package. Create a jdbc driver dirver. Save the url of the database (taking MySQL as an example) in the created string url. If the mysql version is lower than 8.0, the url saving form should be:

String url = "jdbc:mysql://localhost:3306/test"

If the mysql version is 8.0 or above, the url saving form is:

String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";

The mysql version used here is 8.0, So the time zone is added at the end, otherwise the default is UTC time zone, which is 8 hours later than Beijing time.

Then encapsulate the user and password corresponding to the mysql database in the Properties class, and finally create the database connection through the Connection class. The source code is as follows:

		Driver driver = new com.mysql.jdbc.Driver();
        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        /*
        将用户名和密码封装在Properties中
         */
        Properties info = new Properties();
        info.setProperty("user","root");
        info.setProperty("password","ab20010322");

        Connection conn = driver.connect(url,info);

        System.out.println(conn);

The second method: in Based on the first method, use reflection to realize the driver

. Change the first method:

Driver driver = new com.mysql.jdbc.Driver();

to:

Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();

relative to the first method. Two methods have the same functions, but the second method uses reflection to implement the driver, which avoids the use of third-party interfaces and makes the code more portable. The source code of the second method is as follows:

 /*
        使用反射获取Driver类实例
        与Driver driver = new com.mysql.jdbc.Driver()功能相同,只是不适用第三方接口,使得程序具有更好的可移植性
         */
        Class clazz = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();

        /*
        提供要连接的数据库
         */
        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";

        /*
        提供需要的用户名和密码
         */
        Properties info = new Properties();
        info.setProperty("user","root");
        info.setProperty("password","ab20010322");

        Connection connection = driver.connect(url,info);

        System.out.println(connection);

The third method: Use DriveManager(classs) instead of Drive

The source code is as follows:

        Class clazz = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();
        /*
        提供连接信息
         */
        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "ab20010322";
        /*
        注册驱动
         */
        DriverManager.registerDriver(driver);
        /*
        获取连接
         */
        System.out.println(DriverManager.getConnection(url,user,password));

The fourth method: Hide the driver loading method

Change the

Driver driver = (Driver) clazz.newInstance();
DriverManager.registerDriver(driver);

in the third method to

Class.forName("com.mysql.jdbc.Driver");

In this way, you can change the driver loading status Hidden

The source code is as follows:

        String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "ab20010322";
        /*
        加载Driver
         */
        Class.forName("com.mysql.jdbc.Driver");//        Driver driver = (Driver) clazz.newInstance();//        DriverManager.registerDriver(driver);
        /*
        获取连接
         */
        System.out.println(DriverManager.getConnection(url,user,password));

Method 5: Put the basic information required by the database in the jdbc.properties configuration file

For the above four connection methods , all exposing database information. It is not safe to do so. In this regard, we should put the basic information needed by the database in the jdbc.properties configuration file, and then read it out through InputStream. This is safe and our most commonly used database connection method
The configuration file jdbc.properties is as follows:

user=root
password=123456url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
Driver=com.mysql.cj.jdbc.Driver

Note:

1. The configuration file should be placed in the src folder Next

2. Use your own database username and password for user and password

3. If you are using mysql8.0 or above, you should add the time zone at the end when configuring the url file, otherwise An error will be reported

The source code is as follows:

        InputStream inputStream = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties info = new Properties();
        info.load(inputStream);
        
        String user =  info.getProperty("user");
        String password = info.getProperty("password");
        String url = info.getProperty("url");
        String driver = info.getProperty("Driver");

        /*
        加载驱动
         */
        Class.forName(driver);

        /*
        获取连接
         */
        Connection conn = DriverManager.getConnection(url,user,password);
        System.out.println(conn);

Related recommendations:java introductory tutorial

The above is the detailed content of How many ways does java have to connect to mysql? What are the differences?. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

LOL Game Settings Not Saving After Closing [FIXED] LOL Game Settings Not Saving After Closing [FIXED] Aug 24, 2025 am 03:17 AM

IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.

Edit bookmarks in chrome Edit bookmarks in chrome Aug 27, 2025 am 12:03 AM

Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.

Enter key not working on my keyboard Enter key not working on my keyboard Aug 30, 2025 am 08:36 AM

First,checkforphysicalissueslikedebrisordamageandcleanthekeyboardortestwithanexternalone;2.TesttheEnterkeyindifferentappstodetermineiftheissueissoftware-specific;3.Restartyourcomputertoresolvetemporaryglitches;4.DisableStickyKeys,FilterKeys,orToggleK

How to find the max or min value in a Stream in Java How to find the max or min value in a Stream in Java Aug 27, 2025 am 04:14 AM

Use the max() and min() methods to combine Comparator to find the maximum and minimum values ​​in the stream, such as Comparator.naturalOrder() or Integer::compareTo compare basic types; 2. For custom objects, use Comparator.comparing() to compare based on specific fields, such as Person::getAge; 3. Since the result is Optional, the empty stream situation must be handled. You can use isPresent() to check or orElse() to provide default values. It is recommended to use IntStream for basic types to avoid boxing overhead and improve performance. In the end, you should always be properly done.

What is a memory leak in Java? What is a memory leak in Java? Aug 28, 2025 am 05:37 AM

AmemoryleakinJavaoccurswhenunreachableobjectsarenotgarbagecollectedduetolingeringreferences,leadingtoexcessivememoryusageandpotentialOutOfMemoryError.Commoncausesincludestaticcollectionsretainingobjectsindefinitely,unclosedresourceslikestreamsorconne

Solving Common Java NullPointerException Issues with Optional Solving Common Java NullPointerException Issues with Optional Aug 31, 2025 am 07:11 AM

Optional is a container class introduced by Java 8. It is used to clearly indicate that a value may be empty, thereby avoiding NullPointerException; 2. It simplifies nested null checking by providing map, orElse and other methods, preventing methods from returning null and standardizing collection return values; 3. Best practices include only returning values, avoiding the use of fields or parameters, distinguishing orElse from orElseGet, and not calling get() directly; 4. Optional should not be abused. If non-empty methods do not need to be wrapped, unnecessary Optional operations should be avoided in the stream; correct use of Optional can significantly improve code security and readability, but it requires good programming habits.

What is the purpose of the USE statement in MySQL? What is the purpose of the USE statement in MySQL? Aug 27, 2025 am 07:02 AM

TheUSEstatementinMySQLselectsadefaultdatabaseforthecurrentsession,allowingsubsequentoperationstobeperformedwithinthatdatabasecontextwithoutneedingtofullyqualifytablenames;forexample,runningUSEsalessetsthesalesdatabaseasdefault,soquerieslikeSELECTFROM

How to format numbers in Java using DecimalFormat How to format numbers in Java using DecimalFormat Aug 30, 2025 am 03:09 AM

Use DecimalFormat to accurately control digital formats. 1. Use pattern strings such as "#,###.##" for basic formatting, where # represents an optional number, 0 represents a must-display number, is a thousand separator, and is a decimal point; 2. Common modes include "0.00" to retain two decimal places, "0,000.000" to complement zero alignment, etc.; 3. Avoid scientific notation methods, you can setScientificNotation(false) or use a mode with sufficient digits; 4. You can set rounding mode through setRoundingMode(), such as HALF_UP, DOWN, etc.

See all articles