jdbc连接mysql数据库,查询结果封装进实体类

文章目录

    • 1 新建实体类
    • 2 新建表
    • 3 插入数据
    • 4 连接数据库并测试
    • 5 控制台输出

1 新建实体类

public class MessageContent {
    private Integer id;
    private String title;
    private String message;
    private Date createDate;

    @Override
    public String toString() {
        return "MessageContent{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", message='" + message + '\'' +
                ", createDate=" + createDate +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}

2 新建表


CREATE TABLE `msgcontent` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(64) DEFAULT NULL,
  `message` varchar(255) DEFAULT NULL,
  `createDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8

3 插入数据

insert  into 
`msgcontent`(`id`,`title`,`message`,`createDate`) 
values 
(14,'李四','11111111111111111','2018-02-02 20:46:19'),
(15,'今天又降价了','3333333333333333333333','2018-02-02 21:45:57'),
(16,'通知标题1','通知内容1','2018-02-03 11:41:39'),
(17,'通知标题2','通知内容2','2018-02-03 11:52:37'),
(18,'通知标题3','通知内容3','2018-02-03 12:19:41');

4 连接数据库并测试

public class DbConnection {
    public static String url = "jdbc:mysql://localhost:3306/test";
    public static String driver = "com.mysql.jdbc.Driver";
    public static String username = "root";
    public static String password = "123";

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        //加载驱动
        Class.forName(driver);
        Connection connection = null;
        PreparedStatement stat = null;
        ResultSet row = null;
        //创建连接
        try {
            connection = DriverManager.getConnection(url, username, password);
            //构造sql
            String sql = "SELECT * FROM msgcontent limit ?,?";
            stat = connection.prepareStatement(sql);

			stat.setInt(1,0);
            stat.setInt(2,10);
            
            //执行查询
            row = stat.executeQuery();
            while (row.next()) {
                //映射进实体类
                MessageContent messageContent = convertResultToEntity(row, MessageContent.class);
                
				//输出结果
                System.out.println(messageContent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
            if (row != null) {
                row.close();
            }
            if (stat != null) {
                stat.close();
            }
        }
    }

    public static <T> T convertResultToEntity(ResultSet resultSet, Class<T> tClass) throws Exception {
        T t = tClass.newInstance();
        ResultSetMetaData metaData = resultSet.getMetaData();
        for (int i = 0; i < metaData.getColumnCount(); i++) {
            String columnName = metaData.getColumnName(i + 1);

            PropertyDescriptor descriptor = new PropertyDescriptor(columnName, tClass);
            if (descriptor != null) {
                //获得应该用于写入属性值的方法
                Method method = descriptor.getWriteMethod();
                method.invoke(t, resultSet.getObject(columnName));
            }
        }
        return t;
    }
}

5 控制台输出

MessageContent{id=14, title='李四', message='11111111111111111', createDate=2018-02-02 20:46:19.0}
MessageContent{id=15, title='今天又降价了', message='3333333333333333333333', createDate=2018-02-02 21:45:57.0}
MessageContent{id=16, title='通知标题1', message='通知内容1', createDate=2018-02-03 11:41:39.0}
MessageContent{id=17, title='通知标题2', message='通知内容2', createDate=2018-02-03 11:52:37.0}
MessageContent{id=18, title='通知标题3', message='通知内容3', createDate=2018-02-03 12:19:41.0}

你可能感兴趣的:(java)