apache common dbutils1.3 库使用样例

    xiaoxiao2022-06-30  59

    import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; public class Test { /** * @param args */ public static void main(String[] args) { Connection conn = null; // String url = "jdbc:mysql://localhost:3306/test"; String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8"; String jdbcDriver = "com.mysql.jdbc.Driver"; String user = "root"; String password = "root"; if (!DbUtils.loadDriver(jdbcDriver)){ System.out.printf("未找到驱动: %s",jdbcDriver); System.out.println(); return; } try { conn = DriverManager.getConnection(url, user, password); QueryRunner qr = new QueryRunner(); // int [] inid = new int[6]; // for(int i = 1; i < 7; i++){ // inid[i-1] = qr.update(conn, "INSERT INTO users(id,email,password) VALUES(" + (i + 10) + ",'vb" + i +"@q.com','32450')"); // } // // System.out.println(inid); List results = (List) qr.query(conn, "select id,email,password from users", new BeanListHandler(User.class)); for (int i = 0; i < results.size(); i++) { User gb = (User) results.get(i); System.out.println("id:" + gb.getId() + ",email:" + gb.getEmail()); } } catch (SQLException e) { e.printStackTrace(); }finally { DbUtils.closeQuietly(conn); } } }

     

    public class User { private Integer id; private String email; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }

     

     

    此处要注意的是 bean规范,并且 bean 类必须是 public 的

     

     

    http://commons.apache.org/dbutils/examples.html

    jopenid-1.07.jar (523.7 KB)下载次数: 17 commons-dbutils-1.3-bin.zip (543 KB)下载次数: 24 mysql-connector-java-5.1.17-bin.jar (769.5 KB)下载次数: 14
    转载请注明原文地址: https://ju.6miu.com/read-1126061.html

    最新回复(0)