JDBCUtil connection wording mySQL database:
Code:
1 import com.harzone.dongguan.service.JDBCutil; 2 import org.springframework.beans.factory.annotation.Value; 3 import org.springframework.stereotype.Component; 4 5 import java.sql.*; 6 7 @Component 8 public class JDBCUtilImpl implements JDBCutil { 9 @Value("${jdbc.username}") 10 private String username; 11 @Value("${jdbc.password}") 12 private String password; 13 @Value("${jdbc.path}") 14 private String Path; 15 @Value("${jdbc.port}") 16 private String port; 17 @Value("${jdbc.DatabaseName}") 18 private String DatabaseName; 19 20 @Override 21 public Connection getConnection() { 22 try { 23 try { 24 Class.forName("com.mysql.cj.jdbc.Driver"); 25 } catch (ClassNotFoundException e) { 26 e.printStackTrace(); 27 } 28 String url = "jdbc:mysql://" + Path + ":" + port + "/" + DatabaseName + "?characterEncoding=utf8&useSSL=true&serverTimezone=GMT"; 29 Connection connection = DriverManager.getConnection(url, username,password); 30 return connection; 31 } catch (SQLException e) { 32 System.out.println("数据库连接失败。。。。。"); 33 e.printStackTrace(); 34 } 35 return null; 36 } 37 38 @Override 39 public void colseAll(ResultSet rs, Statement statement, Connection conn) { 40 if (rs != null) { 41 try { 42 rs.close(); 43 } catch (SQLException e) { 44 e.printStackTrace(); 45 } 46 } 47 if (statement != null) { 48 try { 49 statement.close(); 50 } catch (SQLException e) { 51 e.printStackTrace(); 52 } 53 } 54 if (conn != null) { 55 try { 56 conn.close(); 57 } catch (SQLException e) { 58 e.printStackTrace(); 59 } 60 } 61 } 62 }
Configure the relevant wording:
# Database connection jdbc: username: root password: root path: localhost Port: 3306 DatabaseName: demo01
Call the relevant wording:
1 PreparedStatement preparedStatement = null; 2 Connection connection = jdbcUtil.getConnection(); 3 //查询字典表获取性别code 4 String sql = "SELECT * FROM dictionary d WHERE d.type='XBDM'"; 5 try { 6 preparedStatement = connection.prepareStatement(sql); 7 ResultSet rs = preparedStatement.executeQuery(); 8 while (rs.next()) { 9 String code_name = rs.getString("code_name"); 10 //Sex determination is obtained and the dictionary table, the corresponding code value returned matches . 11 IF (genderCode.equals (CODE_NAME)) { 12 is String = rs.getString code ( "code" ); 13 is // the code to request the package body, achieve the conversion field 14 bodyMap.put ( "genderCode" , code); 15 } 16 } . 17 } the catch (SQLException E) { 18 is e.printStackTrace (); . 19 }