当前位置:文档之家› JAVA数据库基本操作增删改查(精)

JAVA数据库基本操作增删改查(精)

JAVA 数据库基本操作, 增删改查
package mypack; JAVA 数据库基本操作, 增删改查
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
public class DbOper {//查询多行记录public ArrayList select({Connection conn
=null;
ResultSet rs =null;
try {import java.sql.PreparedStatement; import java.sql.SQLException;
PreparedStatement pstmt =null; ArrayList al =new ArrayList(;
conn =DbConn.getConn(;pstmt =conn.prepareStatement(“select *from titles ”; rs =pstmt.executeQuery(;while (rs.next({Titles t =new
Titles(;t.setTitleid(rs.getString(1;t.setTitle(rs.getString(2;al.add(t;}}catch
(SQLExceptione {
e.printStackTrace(;}finally {try {//TODO 自动生成catch 块if (rs!=null rs.close(;if
(pstmt!=nullpstmt.close(;if (conn!=nullconn.close(;}catch (SQLExceptione {
e.printStackTrace(;}}//TODO 自动生成catch 块
return al; }//查询单个对象public Titles selectOne(Stringtitleid{Connection conn
=null;
ResultSet rs =null;
try {PreparedStatement pstmt =null; Titles t =new Titles(;
conn =DbConn.getConn(;
pstmt.setString(1,titleid;
while (rs.next({pstmt =conn.prepareStatement(“select *from titles where title_id=?”; rs =pstmt.executeQuery(;
t.setTitleid(rs.getString(1;t.setTitle(rs.getString(2;
}}catch (SQLExceptione {
e.printStackTrace(;}finally {try {//TODO 自动生成catch 块if (rs!=null rs.close(;if
(pstmt!=nullpstmt.close(;if (conn!=nullconn.close(;}catch (SQLExceptione {
e.printStackTrace(;}}
}//TODO 自动生成catch 块return t;
//增加记录public boolean insert(Titlest{Connection conn =null;
boolean b =false; try {PreparedStatement pstmt=null;conn
=DbConn.getConn(;pstmt =conn.prep areStatement(“insert into titles(title_id,titlevalues
(?,?”; pstmt.setString(1,t.getTitleid(;pstmt.setString(2,t.getTitle(;
int n =pstmt.executeUpdate(;if(n==1b=true;
}catch (SQLExceptione {
e.printStackTrace(;}finally{try {//TODO 自动生成catch 块
if(pstmt!=nullpstmt.close(;if(conn!=nullconn.close(;}catch (SQLExceptione {
e.printStackTrace(;}}
}//TODO 自动生成catch 块return b;
//删除记录public boolean delete(Stringtitleid{Connection conn =null;
boolean b =false; try {PreparedStatement pstmt=null;conn =DbConn.getConn(;
pstmt.setString(1,titleid;
if(n==1b=true;pstmt =conn.prepareStatement(“delete from titles where title_id=? int n =pstmt.executeUpdate(;
}catch (SQLExceptione {
e.printStackTrace(;}finally{try {//TODO 自动生成catch 块
if(pstmt!=nullpstmt.close(;if(conn!=nullconn.close(;}catch (SQLExceptione {
e.printStackTrace(;}}//TODO 自动生成catch 块return b;
}//修改表public boolean update(Titlest{Connection conn =null;
boolean b PreparedStatement pstmt=null;
try {=false;
set conn =DbConn.getConn(;pstmt =conn.prepareStatement(“update titles
title=?where title_id=?”; pstmt.setString(1,t.getTitle(;pstmt.setString(2,t.getTitleid(;int n =pstmt.executeUpdate(;if(n==1b=true;
}catch (SQLExceptione {
e.printStackTrace(;}finally{try {//TODO 自动生成catch 块
if(pstmt!=nullpstmt.close(;if(conn!=nullconn.close(;}catch (SQLExceptione {
e.printStackTrace(;}}
}}//TODO 自动生成catch 块return b;。

相关主题