JDBC
//加载驱动
Class.forName("oracle.jdbc.OracleDriver");
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接
String url = "jdbc:oracle:thin:@127.0.0.1:1521:jiangwenwen";
String user = "hr";
String password = "qwertyui";
conn = DriverManager.getConnection(url, user, password);
String url = "jdbc:mysql://192.168.235.138:3306/Game";
String user = "root";
String password = "qwertyui";
conn = DriverManager.getConnection(url, user, password);
注释掉bind(服务器)
授权
重启数据库
//准备发送执行sql语句
Connection conn=null;
Statement stem=null;
String sql="insert into departments values(departments_seq.nextval,'招商部',120,1700)";
stem =conn.createStatement();
int n = stem.executeUpdate(sql);
Connection conn=null;
PreparedStatement ps =null;
ResultSet rs=null;
String sql="select * from departments where department_id>? and location_id>?";
String sql = "INSERT INTO users (phone_number, pwd) VALUES (?,?)";
ps=conn.prepareStatement(sql);
ps.setInt(1, 40);
ps.setInt(2, 1700);
ps.execute();
//增删改操作
int n = ps.executeUpdate();
if(n>0){
System.out.println("数据库添加操作成功");
}else{
System.out.println("数据库添加操作失败");
}
//查询操作
while (rs.next()) {
Dept dept =new Dept();
dept.setD_id(rs.getInt("department_id"));//
dept.setD_name(rs.getString("department_name"));
dept.setM_id(rs.getInt("manager_id"));
dept.setLo_id(rs.getInt("location_id"));
list.add(dept);
}
//关闭连接
数据库连接池
C3P0
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "oracle.jdbc.OracleDriver" );
cpds.setJdbcUrl( "jdbc:oracle:thin:@127.0.0.1:1521:jiangwenwen" );
cpds.setUser("jiangwenwen");
cpds.setPassword("qwertyui");
QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
//插入数据
String sql = "INSERT INTO USERS(id,username,Password,Gender,Email,Telephone,INTRODUCE,active_code,state,register_time)
"
+ "VALUES (id_seq.nextval,?,?,?,?,?,?,?,?,?)";
qr.update(sql,user.getUsername(), user.getPassword(), user.getGender(), user.getEmail(),user.getTelephone(), user.getIntroduce(), user.getActive_code(), user.getState(),
user.getRegister_time());
//查询数据
return qr.query("select * from users where active_code = ?",new BeanHandler<Users>(Users.class),active_code);
//更新数据
qr.update("update users set state=1 where active_code=?",active_code);
qr.update("update users set password=?,gender=?,telephone=? where id = ?",user.getPassword(),user.getGender(),user.getTelephone(),user.getId());
Dbutil处理
//批处理
//高维代表循环次数,低维代表每次的参数
Object[][] params = new Object[orderItems.size()][];
for(int i=0;i<params.length;i++) {
//数组中第一个参数代表主单id,第二个参数商品id,第三个参数是商品的购买数量
params[i] = new Object[]{order.getId(),orderItems.get(i).getBook().getId(),orderItems.get(i).getBuy_num()};
}
qr.batch(ManagerThreadLocal.getConnection(),"INSERT INTO orderitem VALUES(?,?,?)", params);
/*
* 使用QueryRunner类,实现对数据表的
* insert delete update
* 调用QueryRunner类的方法 update (Connection con,String sql,Object...param)
* Object...param 可变参数,Object类型,SQL语句会出现?占位符
* 数据库连接对象,自定义的工具类传递
*/
public class QueryRunnerDemo {
private static Connection con = JDBCUtilConfig.getConnection();
public static void main(String[] args) throws SQLException {
// insert();
update();
// delete();
}
/*
* 定义方法,使用QueryRunner类的方法delete将数据表的数据删除
*/
public static void delete() throws SQLException {
// 创建QueryRunner类对象
QueryRunner qr = new QueryRunner();
// 写删除的SQL语句
String sql = "DELETE FROM sort WHERE sid=?";
// 调用QueryRunner方法update
int row = qr.update(con, sql, 8);
System.out.println(row);
/*
* 判断insert,update,delete执行是否成功 对返回值row判断 if(row>0) 执行成功
*/
DbUtils.closeQuietly(con);
}
/*
*
* public static void update()throws SQLException{ //创建QueryRunner类对象
* QueryRunner qr = new QueryRunner(); //写修改数据的SQL语句 String sql =
* "UPDATE sort SET sname=?,sprice=?,sdesc=? WHERE sid=?"; //定义Object数组,存储?中的参数
* Object[] params = {"花卉",100.88,"情人节玫瑰花",4}; //调用QueryRunner方法update int row =
* qr.update(con, sql, params); System.out.println(row);
* DbUtils.closeQuietly(con); }
*
* /* 定义方法,使用QueryRunner类的方法update向数据表中,添加数据
*/
public static void insert() throws SQLException {
// 创建QueryRunner类对象
QueryRunner qr = new QueryRunner();
String sql = "INSERT INTO sort (sname,sprice,sdesc)VALUES(?,?,?)";
// 将三个?占位符的实际参数,写在数组中
Object[] params = { "体育用品", 289.32, "购买体育用品" };
// 调用QueryRunner类的方法update执行SQL语句
int row = qr.update(con, sql, params);
System.out.println(row);
DbUtils.closeQuietly(con);
}
}
/**
* QueryRunner数据查询操作
* 调用QueryRunner类方法query(Connection con,String sql,ResultSetHandler r,Object..params)
* ResultSetHandler r 结果集的处理方式,传递ResultSetHandler接口实现类
* Object...params sql语句的?占位符
*
* 注意:query方法返回值,返回的是T 泛型,具体返回值类型,跟随结果集处理方式变化
* */
public class QueryRunnerDemo02 {
private static Connection con = JDBCUtilConfig.getConnection();
public static void main(String[] args) throws SQLException {
//ArrayHandler();
//arrayListHandler();
//beanHandler();
//beanListHandler();
//columnListHandler();
//scalarHandler();
//mapHandler();
mapListHandler();
}
/**
* 结果集第一种处理方法,ArrayHandler
* 将结果第一行存储到对象数组中Object[]
* @throws SQLException
* */
public static void ArrayHandler() throws SQLException {
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
//调用query执行查询,传递连接对象,SQL语句,结果集处理方式的实现类
//返回对象数组
Object[] result = qr.query(con, sql,new ArrayHandler());
for (Object obj : result) {
System.out.println(obj);
}
}
/**
* 结果集的第二种处理方法,ArrayListHandler
* 将结果集的每一行,封装到对象数组中,出现很多对象数组
* 对象数组存储到List集合
* @throws SQLException
* */
public static void arrayListHandler() throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
//调用query方法,结果集处理的参数上,传递实现类ArrayListHandler
//方法返回值 每行是一个数组
List<Object[]> result = qr.query(con, sql, new ArrayListHandler());
//集合的遍历
for (Object[] objs : result) {
for (Object obj : objs) {
System.out.print(obj+" ");
}
System.out.println();
}
}
/**
* 结果集的第三种处理方法BeanHandler
* 将结果集的第一行数据,封装为JavaBean对象
* 注意:被封装成数据到JavaBean对象,Sort类必须有空参构造
* @throws SQLException
* */
public static void beanHandler() throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
//调用方法,传递结果集实现BeanHandler
//BeanHandler(Class<T> type)
Sort s = qr.query(con, sql,new BeanHandler<Sort>(Sort.class));
System.out.println(s);
}
/**
* 结果集第四种处理方法,BeanListHandler
* 将数据结果集的每一行数据,封装为JavaBean对象
* 多个JavaBean对象封装到List集合中
* @throws SQLException
* */
public static void beanListHandler() throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
//调用方法传递结果集的实现类BeanListHandler
//BeanListHandler(Class<T> type)
List<Sort> list = qr.query(con, sql, new BeanListHandler<Sort>(Sort.class));
for (Sort s : list) {
System.out.println(s);
}
}
/**
* 结果集第五种处理方法,ColumnListHandler
* 结果集,指定列的数据,存储到List集合中
* List<Object> 每个列数据类型不同
* @throws SQLException
* */
public static void columnListHandler() throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
//调用方法query,传递结果集实现类ColumnListHandler
//实现类构造方法,使用字符串的列名
List<Object> list = qr.query(con, sql, new ColumnListHandler<Object>("sname"));
for (Object obj : list) {
System.out.println(obj);
}
}
/**
* 结果集第六种处理方法、
* 对于查询后,只有一个结果
* @throws SQLException
* */
public static void scalarHandler() throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT COUNT(*) FROM sort";
//调用方法query,传递结果集处理类ScalarHandler
long count = qr.query(con,sql,new ScalarHandler<Long>());
System.out.println(count);
}
/**
* 结果集的第七种处理方式,MapHandler
* 将结果集第一行数据,封装到Map集合中
* Map<键,值> 键:列名 值:这列数据
* @throws SQLException
* */
public static void mapHandler() throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
//调用方法query,传递结果集实现类MapHandler
//返回值:Map集合,Map接口实现类 泛型
Map<String,Object> map = qr.query(con, sql,new MapHandler());
for (String key : map.keySet()) {
System.out.println(key+"..."+map.get(key));
}
}
/**
* 结果集第八种处理方法,MapListHandler
* 将结果集每一行存储到Map集合,键:列名 值:数据
* Map集合过多,存储到List集合
* @throws SQLException
* */
public static void mapListHandler() throws SQLException{
QueryRunner qr = new QueryRunner();
String sql = "SELECT * FROM sort";
//调用方法query,传递结果集实现类MapListHander
//返回值List集合,存储的是Map集合
List<Map<String, Object>> list = qr.query(con, sql,new MapListHandler());
for (Map<String, Object> map : list) {
for (String key : map.keySet()) {
System.out.print(key+"..."+map.get(key));
}
System.out.println();
}
}
}
JDBC如何实现模糊查询
//第一种
String sql = "select studentname, age, phone, address, other from customer where studentname like ? ";
pstmt.setString(1, "%" + customername + "%" );
//第二种
String sql = "select customercode, customername, phone, address, relationman, other from customer"
+ " where customername like "%"?"%" ";
pstmt.setString(1, customername);