1. How to get a database connection
TestConnection
package com.aff.connection; import java.io.InputStream; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.junit.Test; public class TestConnection { // Method 1 @Test public void testConnection () throws SQLException { // Get Driver implementation object Driver driver = new com.mysql.jdbc.Driver (); // jdbc: mysql protocol // localhost ip Address // 3306 default mysql port number // test database name String url = "jdbc: mysql: // localhost: 3306 / test" ; // username and password are encapsulated in Properties Properties info = new Properties (); info.setProperty("user", "root"); info.setProperty("password", "123456"); Connection conn = driver.connect(url, info); System.out.println(conn); } // Method 2: For iteration of method 1, no third-party APIs appear in the following program, making the program more portable @Test public void testConnection2 () throws Exception { // Get Driver implementation class object : Use reflection Class clazz = Class.forName ("com.mysql.jdbc.Driver" ); Driver driver = (Driver) clazz.newInstance(); // Database required for connection String url = "jdbc: mysql: // localhost: 3306 / test" ; // Provide the username and password required for connection Properties info = new Properties (); info.setProperty("user", "root"); info.setProperty("password", "123456"); // Get connection Connection conn = driver.connect (url, info); System.out.println(conn); } // Method 3: Use DriverManager to manage @Test public void testConnection3 () throws Exception { // Get the object of Driver implementation class Class clazz = Class.forName ("com.mysql.jdbc.Driver" ); Driver driver = (Driver) clazz.newInstance(); // Provide basic information for three connections String url = "jdbc: mysql: // localhost: 3306 / test" ; String user = "root"; String password = "123456"; // Get DriverManager Driver // Register Driver DriverManager.registerDriver (driver); // Get connection Connection conn = DriverManager.getConnection (url, user, password); System.out.println(conn); } // Method four: Optimize @Test public void testConnection4 () throws Exception on the basis of three { // 1. Provide basic information of three connections String url = "jdbc: mysql: // localhost: 3306 / test" ; String user = "root"; String password = "123456"; // 2. Load the driver. In the driver's implementation class of mysql, the driver has been registered Class.forName ("com.mysql.jdbc.Driver" ); // 3. Get connection Connection conn = DriverManager.getConnection (url, user, password); System.out.println(conn); } // Method 5: Final version, declare the 4 information needed for database connection in the configuration file, and connect to the database by reading the configuration file /* * Benefits: 1. Realize the separation of data and code, realize decoupling * 2. If you need to modify the configuration information, you can avoid re-packaging the program */ @Test public void testConnection5 () throws Exception { // 1. Read the 4 basic information in the configuration file, through the class loader InputStream is = TestConnection. class .getClassLoader (). getResourceAsStream ("jdbc.properties" ); Properties pro = new Properties (); // Load the is file pro.load (is); // Read the configuration information in it String user = pro.getProperty ("user" ); String url = pro.getProperty("url"); String password = pro.getProperty("password"); String driverClass = pro.getProperty("driverClass"); // 2. Load the driver Class.forName (driverClass); // 3. Get connection Connection conn = DriverManager.getConnection (url, user, password); System.out.println(conn); } }
2. The disadvantages of Statement operation database: need to spell sql statement, and there is a problem of SQL injection
Example: testLogin
package com.aff.connection; import java.io.InputStream; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import java.util.Scanner; import org.junit.Test; public class StatementTest { // Disadvantages of using Statement: need to spell sql statement, and there is a problem of SQL injection @Test public void testLogin () { Scanner scan = new Scanner(System.in); System.out.print ( "User name:" ); String userName = scan.nextLine(); System.out.print ( "Password:" ); String password = scan.nextLine(); // SELECT user,password FROM user_table WHERE USER = '1' or ' AND // PASSWORD = ' // ='1' or '1' = '1'; String sql = "SELECT user,password FROM user_table WHERE user = '" + userName + "' AND PASSWORD = '" + password + "'"; User user = get(sql, User.class); if (user != null) { System.out.println ( "Login successful!" ); } else { System.out.println ( "Wrong username or password!" ); } } // Use Statement to query the data table public <T> T get (String sql, Class <T> clazz) { T t = null; Connection conn = null; Statement st = null; ResultSet rs = null ; try { // 1. Load configuration file InputStream is = StatementTest. Class .getClassLoader (). GetResourceAsStream ("jdbc.properties" ); Properties pros = new Properties(); pros.load(is); // 2. Read configuration information String user = pros.getProperty ("user" ); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); // 3. Load the driver Class.forName (driverClass); // 4. Get connection conn = DriverManager.getConnection (url, user, password); st = conn.createStatement(); rs = st.executeQuery(sql); // Get the metadata of the result set ResultSetMetaData rsmd = rs.getMetaData (); // Get the number of columns in the result set int columnCount = rsmd.getColumnCount (); if (rs.next()) { t = clazz.newInstance(); for ( int i = 0; i <columnCount; i ++ ) { // // 1. Get the name of the column // String columnName = rsmd.getColumnName (i + 1); // 1. Get the alias of the column String columnName = rsmd.getColumnLabel (i + 1 ); // 2. Obtain the data in the corresponding data table according to the column name Object columnVal = rs.getObject (columnName); // 3. Pack the data obtained in the data table into the object Field field = clazz.getDeclaredField (columnName); field.setAccessible(true); field.set(t, columnVal); } return t; } } catch (Exception e) { e.printStackTrace (); } finally { // Close resource if (rs! = null ) { try { rs.close(); } catch (SQLException e) { e.printStackTrace (); } } if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace (); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace (); } } } return null; } }
User
package com.aff.connection; public class User { private String user; private String password; public User() { } public User(String user, String password) { super(); this.user = user; this.password = password; } @Override public String toString() { return "User [user=" + user + ", password=" + password + "]"; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }