String sql="select r.id,r.did as did,u.uname,d.dname,r.lendTime,r.returnTime from users u,records r,dvds dwhere u.id=r.uid and r.did=d.id and u.uname=?";
这是一条进行三表连接查询的sql语句,select关键字后面的是作为查询后所得结果的列名,虽然records表里的did与dvds表里的id是相同的值,但是红体字处写r.did与写d.id是不同的,前者以did作为列名,后者将以id作为列名(as did并无实际用途,可忽略),这很重要,列名会影响查询操作时获取的数据值。
下面贴入一段数据库JDBC编程通用的增删查改代码
public class BaseDao {
private static final String DRIVER="com.mysql.jdbc.Driver";
private static final String URL="jdbc:mysql://127.0.0.1:3306/mysql";
private static final String USER="root";
private static final String PASSWORD="8008008820";
public Connection getConn(){
Connection conn=null;
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn=DriverManager.getConnection(URL,USER,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/*
* 关闭所有资源
*/
public void closeAll(ResultSet rs,PreparedStatement pstmt,Connection conn){
if(rs!=null){
try {
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//增删改的功能
public boolean operUpdate(String sql,List<Object> parms){
int res=0;
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
conn=getConn();
try {
pstmt=conn.prepareStatement(sql);//装载sql语句
if(parms!=null){
for(int i=0;i<parms.size();i++){
pstmt.setObject(i+1, parms.get(i));
}
}
res=pstmt.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
closeAll(rs,pstmt,conn);
}
return res>0 ? true:false;
}
//查询的功能
public<T> List<T> operQuery(String sql,List<Object> params,Class<T> cla) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
conn=getConn();
List<T> data=new ArrayList<T>();
try {
pstmt=conn.prepareStatement(sql);//装载sql语句
if(params!=null){
for(int i=0;i<params.size();i++){
pstmt.setObject(i+1, params.get(i));
}
}
rs=pstmt.executeQuery();
//把查询结果封装成对应的实体类对象
ResultSetMetaData rsd=rs.getMetaData();//得到记录元数据对象
while(rs.next()){
T m=cla.newInstance();
for(int i=0;i<rsd.getColumnCount();i++){
String col_name=rsd.getColumnName(i+1);
Object value =rs.getObject(col_name);
Field field=cla.getDeclaredField(col_name);
field.setAccessible(true);
//value其实就是m对象里某个成员变量的值
field.set(m,value);
}
data.add(m);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
closeAll(rs,pstmt,conn);
}
return data;
}
}