JDBCUtil连接mySQL数据库的写法:
代码:
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 }
配置相关写法:
#数据库连接 jdbc: username: root password: root path: localhost port: 3306 DatabaseName: demo01
调用相关的写法:
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 //判断得到的性别和字典表的性别,匹配返回对应的code值 11 if (genderCode.equals(code_name)) { 12 String code = rs.getString("code"); 13 //将code封装到请求体,实现转换字段 14 bodyMap.put("genderCode", code); 15 } 16 } 17 } catch (SQLException e) { 18 e.printStackTrace(); 19 }
原文:https://www.cnblogs.com/wangquanyi/p/11329848.html