第一个DBUtils程序

本章讲解如何使用DBUtils库创建简单JDBC应用程序的入门程序。将告诉你如何打开数据库连接,执行SQL查询以及获取查询结果。

1 编写Customer实体类

Customer:

package com.yiidian.domain;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class Customer {
    private Integer id;
    private String name;
    private String gender;
    private String telephone;
    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

2 编写DBUtils入门程序

FirstDemo:

package com.yiidian.dbutils;

import com.yiidian.domain.Customer;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class FirstDemo {
    // 驱动程序
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    // URL连接
    static final String DB_URL = "jdbc:mysql://localhost:3306/test";

    //数据库信息
    static final String USER = "root";
    static final String PASS = "root";

    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        QueryRunner queryRunner = new QueryRunner();

        //第一步:注册驱动程序
        DbUtils.loadDriver(JDBC_DRIVER);

        //第二步:创建连接
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        //第三步: 创建ResultSetHandler对象
        ResultSetHandler<Customer> resultHandler = new BeanHandler<Customer>(Customer.class);

        try {
            Customer customer = queryRunner.query(conn, "SELECT * FROM customer where name = ?",
                    resultHandler, "张三");
            //第四步:展示结果
            System.out.print("编号: " + customer.getId());
            System.out.print(", 用户名: " + customer.getName());
            System.out.print(", 性别: " + customer.getGender());
            System.out.print(", 联系电话: " + customer.getTelephone());
            System.out.println(", 住址: " + customer.getAddress());
        } finally {
            //第五步:关闭连接
            DbUtils.close(conn);
        }
    }
}

3 运行测试

热门文章

优秀文章