浏览 4360 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-09-14
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 的 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |