1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| package cn.vidorra.todo;
import cn.vidorra.todo.pojo.TodoListEntity;
import java.sql.*; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger;
public class JDBCExample { private Connection getConnection() { Connection connection = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://127.0.0.1:3306/vidorra?serverTimezone=PRC&useUnicode=true&characterEncoding=utf8&useSSL=false"; String user = "root"; String password = "123456"; connection = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException | SQLException e) { Logger.getLogger(JDBCExample.class.getName()).log(Level.SEVERE, null, e); return null; } return connection; }
public TodoListEntity getTodo(Long id) { Connection connection = getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { String sql = "select * from todo_list where id = ?"; ps = Objects.requireNonNull(connection).prepareStatement(sql); ps.setLong(1, id); rs = ps.executeQuery(); if (rs.next()) { long todoID = rs.getLong("id"); long todoUID = rs.getLong("uid"); String todoContents = rs.getString("contents"); byte todoStatus = rs.getByte("status"); int todoCreateTime = rs.getInt("create_time"); int todoUpdateTime = rs.getInt("update_time");
return new TodoListEntity( todoID, todoUID, todoContents, todoStatus, todoCreateTime, todoUpdateTime ); } } catch (SQLException e) { Logger.getLogger(JDBCExample.class.getName()).log(Level.SEVERE, null, e); } finally { this.close(rs, ps, connection); } return null; }
private void close(ResultSet rs, Statement stmt, Connection connection) { try { if (rs != null && !rs.isClosed()) { rs.close(); } } catch (SQLException e) { Logger.getLogger(JDBCExample.class.getName()).log(Level.SEVERE, null, e); }
try { if (stmt != null && !stmt.isClosed()) { stmt.close(); } } catch (SQLException e) { Logger.getLogger(JDBCExample.class.getName()).log(Level.SEVERE, null, e); }
try { if (connection != null && !connection.isClosed()) { connection.close(); } } catch (SQLException e) { Logger.getLogger(JDBCExample.class.getName()).log(Level.SEVERE, null, e); } }
public static void main(String[] args) { JDBCExample example = new JDBCExample(); TodoListEntity entity = example.getTodo(1L); System.err.println("todo => " + entity.toString()); } }
|