java Connect database 5 ways to interpret _java_ script home

5 ways java connects to a database

Updated: Apr 02, 2024 08:59:23 by thulium_
This article mainly introduces the java connection database 5 ways, has a good reference value, I hope to help you, if there is a mistake or not considered completely, please feel free to advise.

Method 1: Import third-party library driver classes

This loading method has been used in the introduction of jdbc, and the driver belongs to a third-party library. For static loading, poor flexibility, dependency grab

Method 2: Using the reflection mechanism

Mode one and mode two codes

package com.hsp.edu; import com.mysql.cj.jdbc.Driver; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; // 5 ways java can obtain a connection public class JdbcConnect {public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { connect01(); connect02(); } // Method 1: Import the third-party library Driver class public static void connect01() throws SQLException {// Obtain the driver Driver driver = new Driver(); / / get connection String url = "JDBC: mysql: / / localhost: 3306 / JDBC? serverTimezone=UTC&useSSL=false&useSer" + "verPrepStmts=true&characterEncoding=utf-8&useSSL=false"; // Put the user name and password into the Properities object. Properties properties = new Properties(); properties.setProperty("user","root"); setProperty("password","888888"); // user properties.setProperty("password","888888"); final Connection connect = driver.connect(url, properties); // password Final connection connect = driver.connect(URL, properties); System.out.println(connect); // Method 2: Use reflection to load the Driver: Dynamic loading, more flexible, Reduce dependencies public static void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, NoSuchMethodException InvocationTargetException {/ / get Driver Class bytecode file object final Class <? > clazz = Class.forName("com.mysql.cj.jdbc.Driver"); // Note: When a bytecode file object is used to obtain a Driver object, the direct newInstance is prompted by the idea that final Constructor<? > Constructor = clazz.getDeclaredConstructor(); final Driver driver = (Driver)Constructor.newInstance(); String url = "jdbc:mysql://localhost:3306/jdbc? serverTimezone=UTC&useSSL=false&useSer" + "verPrepStmts=true&characterEncoding=utf-8&useSSL=false"; // Put the user name and password into the Properities object. Properties properties = new Properties(); properties.setProperty("user","root"); setProperty("password","888888"); // user properties.setProperty("password","888888"); final Connection connect = driver.connect(url, properties); // password Final connection connect = driver.connect(URL, properties); System.out.println(connect); }}

Method 3: Use the DriverManager class

// Method 3: Use the DriverManager replacement Driver public static void connect03 () throws SQLException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException, ClassNotFoundException {// The DriverManager Class supports a better way to get connections by taking the user and password directly as parameters instead of storing them in Properities final Class<? > clazz = Class.forName("com.mysql.cj.jdbc.Driver"); final Constructor<? > constructor = clazz.getDeclaredConstructor(); final Driver driver =(Driver)constructor.newInstance(); / / create the url and user and password String url = "JDBC: mysql: / / localhost: 3306 / JDBC? serverTimezone=UTC&useSSL=false&useSer" + "verPrepStmts=true&characterEncoding=utf-8&useSSL=false"; String user = "root"; final String password = "888888"; DriverManager.registerDriver(driver); / / registered Driver to drive the final Connection Connection = DriverManager. GetConnection (url, user, password); System.out.println(connection); }

Method 4: Automatic Driver registration when loading the driver class (to simplify the code)

Driver class underlying source code

Static block of code: executes once when the class is loaded

From the source code of the Driver class above, it can be seen that when loading the Driver class, its static code block has completed the registration of the driver

// Method 4: Automatic registration is done when the Driver is loaded (this method is used most often, Recommended:) public static void connect04() throws ClassNotFoundException, SQLException {// The Driver class is loaded using reflection. Class.forName("com.mysql.cj.jdbc.Driver") is registered. String url = "jdbc:mysql://localhost:3306/jdbc? serverTimezone=UTC&useSSL=false&useSer" + "verPrepStmts=true&characterEncoding=utf-8&useSSL=false"; String user = "root"; String password="888888"; final Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); }

Method 5: Write the information to the configuration file

One question: why not write 'Class.forName("com.mysql.cj.jdbc.Driver"); Can I also get a connection?

services under META-INF in the driver file have a com.mysql.cj.jdbc.Driver file that already records the loaded class names.

Our program will load directly from the contents of the file

With configuration files, we don't have to change the code when we need to change it, we just change the configuration file

Clarification: There is no direct relationship between the Properties class and the properties file (it was previously thought that if you created a properies file, a Properties object already existed)

The Properties class is stored in the same format as the properties file (in the form of key-value pairs), but it still needs to read the data in the file to the program configuration file directory when it is used

// Method 5: Further optimization, Writes information to the configuration file public static void connect05() throws IOException, ClassNotFoundException, SQLException {// Obtain configuration file information from the Properties object. properties = new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); // The information about the configuration file is read into properties. // Obtain related information. final String user = properties.getProperty("user"); // User final String password = properties.getProperty("password"); // User final string password = properties.getproperty ("password"); // password final String url = properties.getProperty("url"); //url final String driver = properties.getProperty("driver"); Class.forName(driver); / / registered to drive the final Connection Connection = DriverManager. GetConnection (url, user, password); // Get the connection System.out.println(connection); }

Classroom exercise

Properties file

package com.hsp; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /* Refer to the teacher's code and use Method 5 to complete 1. Create news Table 2. Add 5 records using jdbc 3. Change the content of record id=1 to a new record */ public class Jdbc02 {public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {// Preposition: Get the information in the configuration file. Properties properties = new Properties(); properties.load(new FileInputStream("src\\mysql1.properties")); // Read information to the collection final String driver = properties.getProperty("driver"); // Get the full class name final String url = properties.getProperty("url"); // Get url final String user = properties.getProperty("user"); // Obtain the user name final String password = properties.getProperty("password"); // Get the password System.out.println(properties); //1. Register the driver Class.forName(driver); / / 2. Get connect final Connection Connection = DriverManager. GetConnection (url, user, password); Run the SQL statement //String sql1 = "CREATE TABLE news(id INT,content VARCHAR(32))"; //3. String sql2="INSERT INTO news VALUES (1,' resident health '),(2,' commodity health '),(3,' giant panda ')"; String sql3="UPDATE news SET content=' Hubei 'WHERE id=1;" ; final Statement statement = connection.createStatement(); //final int row1 = statement.executeUpdate(sql1); final int row2 = statement.executeUpdate(sql2); // Return the number of affected rows. Final int row2 = statement.executeUpdate(SQL2); final int row3 = statement.executeUpdate(sql3); // Return the number of affected rows. Final int row3 = statement.executeUpdate(sql3); // : Check whether the command is executed successfully. /*if(row1! =0){System.out.println(" Executed successfully "); }else {System.out.println(" Execution failed "); }*/ if (row2! =0){System.out.println(" Executed successfully "); }else {System.out.println(" Execution failed "); } if(row3! =0){System.out.println(" Executed successfully "); }else {System.out.println(" Execution failed "); } //4. close the resource statement.close(); connection.close(); }}

Sum up

The above is personal experience, I hope to give you a reference, but also hope that you support the script home.

Related article

Latest comments