1. encapsulated javabean
Package com. csdn. hbsi. domain;
Public class User {
Private int id;
Private String name;
Private double price;
Private String author;
Private String description;
Public int getId (){
Return id;
}
Public void setId (int id ){
This. id = id;
}
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
Public double getPrice (){
Return price;
}
Public void setPrice (double price ){
This. price = price;
}
Public String getAuthor (){
Return author;
}
Public void setAuthor (String author ){
This. author = author;
}
Public String getDescription (){
Return description;
}
Public void setDescription (String description ){
This. description = description;
}
}
2. package com. csdn. hbsi. demo;
Import java. SQL. SQLException;
Import java. util. List;
Import org. apache. commons. dbutils. QueryRunner;
Import org. apache. commons. dbutils. ResultSetHandler;
Import org. apache. commons. dbutils. handlers. BeanHandler;
Import org. apache. commons. dbutils. handlers. BeanListHandler;
Import org. junit. Test;
Import com. csdn. hbsi. domain. User;
Import com. csdn. hbsi. utils. DBManager;
Public class demo_crud {
@ Test
Public void insert () throws SQLException {
QueryRunner runner = new QueryRunner (DBManager. getDataSource ());
String SQL = "insert into book (id, name, price, author, description) values (?,?,?,?,?) ";
Object params [] = {5, "cc", "66", "cccc", "dd "};
Runner. update (SQL, params );
}
@ Test
Public void update () throws SQLException {
QueryRunner runner = new QueryRunner (DBManager. getDataSource ());
String SQL = "update book set name =? Where id =? ";
Object params [] = {"eeee", 3 };
Runner. update (SQL, params );
}
@ Test
Public void delete () throws SQLException {
QueryRunner runner = new QueryRunner (DBManager. getDataSource ());
String SQL = "delete from book where id =? ";
Object params [] = {3 };
Runner. update (SQL, params );
}
@ SuppressWarnings ("deprecation ")
@ Test
Public void find () throws SQLException {
QueryRunner runner = new QueryRunner (DBManager. getDataSource ());
String SQL = "select * from book where id =? ";
User user = (User) runner. query (SQL, 1, new BeanHandler (User. class ));
System. out. println (user );
}
@ Test
Public void findall () throws SQLException {
QueryRunner runner = new QueryRunner (DBManager. getDataSource ());
String SQL = "select * from book ";
List list = (List) runner. query (SQL, new BeanListHandler (User. class ));
System. out. println (list. size ());
}
}
3. Configuration File
Com. mysql. jdbc. Driverjdbc: mysql: // localhost: 3306/testroot123510530com. mysql. jdbc. Driverjdbc: mysql: // localhost: 3306/testroot123510530
4. package com. csdn. hbsi. utils;
Import com. mchange. v2.c3p0. ComboPooledDataSource;
Public class DBManager {
Private static ComboPooledDataSource ds = null;
Static {
Ds = new ComboPooledDataSource ();
}
Public static ComboPooledDataSource getDataSource (){
Return ds;
}
}