java database connectivity java 与数据库的连接
服务器 (db):
客户端 (java):
1.接收数据
2.组装sql
3.发送SQL(与数据库建立联系)
4.分析结果
示例:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
*
* 优化:
* 1.异常捕获
* 2.数据的配置信息使用配置文件动态读取
* @author zhuch
*
*/
public class JDBCSimpleDemo02 {
public static void main(String[] args){
Properties pro = new Properties();
try {
pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
//1.加载驱动(选择哪一个数据库)
Class.forName(pro.getProperty("driver"));
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2.获取连接(与数据库连接上)
Connection conn=null;
Statement state=null;
ResultSet result=null;
try {
conn = DriverManager.getConnection(
pro.getProperty("url"),
pro.getProperty("name"),
pro.getProperty("pwd"));
//3.准备sql
String sql="select empno,ename from emp";//注意sql语句后面不要添加分号
//4.获取处理块(打包发送)
state = conn.createStatement();
//5.执行完毕得到结束,接收结果集
result = state.executeQuery(sql);
//6.处理数据
while(result.next()){
int i= result.getInt("empno");
String name = result.getString("ename");
System.out.println(i+"-->"+name);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
//7.关闭
try {
if(result!=null){
result.close();
}
if(state!=null){
state.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* jdbc 工具类
* 1.加载驱动
* 2.获取连接
* 3.关闭
* @author zhuch
*
*/
public class DBUtils {
private static Properties pro = new Properties();
//类第一次加载完之后只执行一次(加载驱动)
static{
try {
pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
//1.加载驱动(选择哪一个数据库)
Class.forName(pro.getProperty("driver"));
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException{
Connection conn=null;
conn = DriverManager.getConnection(
pro.getProperty("url"),
pro.getProperty("name"),
pro.getProperty("pwd"));
return conn;
}
//关闭
public static void close(ResultSet result,Statement state,Connection conn){
//7.关闭
try {
if(result!=null){
result.close();
}
if(state!=null){
state.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
示例:
/*
* 模拟转账(方法)
*/
public static void test(){
Connection conn=null;
PreparedStatement state=null;
try {
//获取连接
conn=DBUtils.getConnection();
//设置手动提交
conn.setAutoCommit(false);
//2.sql
String sql="update hehe set money=money-100 where name='lisi'";
//3.预处理块
state = conn.prepareStatement(sql);
//4.执行sql,获取结果
int row = state.executeUpdate();
System.out.println(row);
//sql2
String sql2="update hehe set money=money+100 where name='zhangsan'";
//预处理块
state=conn.prepareStatement(sql2);
//执行sql,获取结果
int row2=state.executeUpdate();
System.out.println(row2);
//处理结果
if(row>0 && row2>0){
System.out.println("转账成功");
conn.commit();//提交
}else{
System.out.println("转账失败");
conn.rollback();//回滚
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtils.close(null, state, conn);
}
}
作用:
public class User {
private int id;
private String uname;
private int upwd;
public User() {
super();
}
public User(int id, String uname, int upwd) {
super();
this.id = id;
this.uname = uname;
this.upwd = upwd;
}
@Override
public String toString() {
return "User [id=" + id + ", uname=" + uname + ", upwd=" + upwd + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getUpwd() {
return upwd;
}
public void setUpwd(int upwd) {
this.upwd = upwd;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((uname == null) ? 0 : uname.hashCode());
result = prime * result + upwd;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
if (uname == null) {
if (other.uname != null)
return false;
} else if (!uname.equals(other.uname))
return false;
if (upwd != other.upwd)
return false;
return true;
}
}
DaseDao.java
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 数据库通过访问对象
* 1.增删改的功能
* 2.查询的功能
* @author zhuch
*
*/
public class BaseDao {
//查询 返回值List 参数:sql 值
public List testQuery(String sql,Class cls,Object ... args){
List ls=new ArrayList();
boolean flag=false;
Connection conn=null;
PreparedStatement state=null;
ResultSet result=null;
ResultSetMetaData meta=null;
try {
conn=DBUtils.getConnection();
state = conn.prepareStatement(sql);
//为?赋值
if(args!=null && args.length!=0){
for(int i=0;i<=args.length-1;i++){
state.setObject(i+1,args[i]);
}
}
//结果集
result=state.executeQuery();
//结果集的原信息对象
meta = result.getMetaData();
int columnNum = meta.getColumnCount();
while(result.next()){
//进了就有一个对象
T t = cls.newInstance();//默认调用空构造
for(int i=1;i<=columnNum;i++){
//2.从结果集中获取每一个字段的值
Object value = result.getObject(i);
//1.创建一个对应类型的成员属性 getDeclaredField(String name)
String name = meta.getColumnLabel(i);
//3.获取对应java类中的对应属性
Field field = cls.getDeclaredField(name);
field.setAccessible(true);//设置值
//4.给这个属性赋值
field.set(t, value);
field.setAccessible(false);
}
//5.把对象放入list容器
ls.add(t);
}
//System.out.println(meta.getColumnCount());
//System.out.println(meta.getColumnLabel(1));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtils.close(result, state, conn);
}
return ls;
}
//增删改
public boolean testUpdate(String sql,Object ... args){
boolean flag=false;
Connection conn=null;
PreparedStatement state=null;
try {
conn=DBUtils.getConnection();
state = conn.prepareStatement(sql);
//为?赋值
for(int i=0;i<=args.length-1;i++){
state.setObject(i+1,args[i]);
}
int row=state.executeUpdate();
if(row>0){
flag=true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtils.close(null, state, conn);
}
return flag;
}
/*
* 可变参数 相同的数据类型的0~多个参数
* 1.数据类型...参数名,0~n个
* 2.必须定义在参数列表的最后
* 3.通过数组的操作方式去使用,会隐式的为可变参数定义一个数组
*/
/*public static void test(int a,String ...s){
}*/
}
实用:Test.java
import java.util.List;
import com.shsxt.bean.User;
import com.shsxt.utils.BaseDao;
public class Test {
public static void main(String[] args) {
//BaseDao base=new BaseDao();
//String sql="insert into sxt_user values(sq_num.nextval,?,?)";
String sql="delete from sxt_user where uname=?";
//boolean flag=base.testUpdate(sql, "zcp1","123");
/*boolean flag=base.testUpdate(sql, "zcp1");
if(flag){
System.out.println("操作成功");
}else{
System.out.println("操作失败");
}*/
BaseDao base=new BaseDao();
//String sql2="select id,uname,upwd from sxt_user";
String sql2="select uname \"uname\" from sxt_user";
List ls = base.testQuery(sql2, User.class);
System.out.println(ls);
}
}