5 ways java connects to a database
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.
- Example of Java connecting to MySQL database and implementing data interaction
- Super detailed tutorial on Java connecting to SQL Server database
- Record the complete procedure for connecting Java to the Oracle database
- Configure idea to connect Java with database to implement a simple library management system
- java connection database knowledge summary and operation application
Related article
-
The SpringBoot integrated jersey packaging jar could not find a handler for class
This article mainly introduces the SpringBoot integrated jersey packaging jar can not find the class processing method, the article through the code examples introduced in very detail, to everyone's study or work has certain help, need friends can refer to2024-03-03 -
Spring MVC 4.1.3 + MyBatis zero-based Web development framework (annotation mode)
This article mainly introduces Spring MVC 4.1.3 + MyBatis zero foundation to build a Web development framework (annotation mode), has a certain reference value, interested partners can refer to it.2017-03-03 -
Detail the basic operation of IO byte stream in Java (copying files) and test performance
This article mainly introduces the basic operation of IO byte stream in Java (copy files) and test performance, the article introduces very detailed through the example code, which has certain reference value for everyone's study or work, and the friends who need to study together with Xiaobian below2019-04-04 -
The springmvc view parses the process code instance
This article mainly introduces the springmvc view analysis process code example, the article through the example code introduction is very detailed, for everyone's study or work has a certain reference learning value, need friends can refer to it2020-01-01 -
java.text.DecimalFormat is a decimal format
This article mainly introduces the java.text.DecimalFormat class decimal format method in detail for everyone, has a certain reference value, interested partners can refer to it2018-03-03 -
JavaWeb project audio resources playback implementation method detailed explanation
This article mainly introduces the JavaWeb project audio resource playback method detailed explanation, the article through the example code to introduce very detailed, for everyone's study or work has a certain reference learning value, the need of friends can refer to2019-10-10 -
spring boot integrates the redis primary/secondary sentinel mode
This article mainly introduces the integration of spring boot with redis master-slave sentinel, which has a good reference value and hopes to be helpful to you. If there are mistakes or incomplete areas, please feel free to comment2022-03-03 -
Eureka source code core class preparation knowledge
This article mainly introduces the Eureka source code core class preparation knowledge detailed, the need of friends can use for reference, I hope to be helpful, I wish you a lot of progress, early promotion and pay rise2022-10-10 -
In-depth analysis of Java8 new features Date and time _ Power Node Java Academy Collation
This article mainly introduces the Java8 new features of in-depth analysis of date and time _ Power node Java Academy collation, need friends can refer to the next2017-06-06 -
Description of SpringBoot optimization method for connection number
The biggest benefit of SpringBoot development is to simplify the configuration, built-in Tomcat, the following article mainly introduces the relevant information about SpringBoot to optimize the number of connections, the article through the example code is very detailed, the need for friends can refer to2023-06-06
Latest comments