//:Db2ConnTest
/**
*功能:实现连接DB2数据库,并实现基本获取数据功能
*jiangbin
*/
import java.sql.*;
import java.util.*;
@SuppressWarnings("unchecked")
public class Db2ConnTest{
Connection conn;
Statement stat;
ResultSet rs;
ResultSetMetaData rsmd;
PreparedStatement pstat; //预编译
List ll = new ArrayList();
/**
*建立连接
*/
public void connDb2(){
try{
//第一步:加载驱动
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
//第二步:得到连接
conn = DriverManager.getConnection("jdbc:db2:mydb","db2admin","123");
//第三步:建立statement,同一时间每个 Statement 对象在只能打开一个 ResultSet 对象。
stat = conn.createStatement();
}
catch(ClassNotFoundException ee){
System.out.println("ClassNotFoundException:"+ee.getMessage());
}
catch(SQLException e){
System.out.println(e);
}
}
/**
*断开连接
*/
public void closeDb2(){
try{
if(rs!=null) rs.close();
if(stat!=null) stat.close();
if(conn!=null) conn.close();
}
catch(SQLException e){
System.out.println(e);
}
}
/**
*查询数据
*/
public void searchData(){
try{
//得到结果集
rs = stat.executeQuery("select * from db.tblStudent");
//用于获取关于 ResultSet 对象中列的类型和属性信息的对象
rsmd = rs.getMetaData();
while(rs.next()){
Map rowData = new HashMap();
for(int i=1;i<=rsmd.getColumnCount();i++)
rowData.put(rsmd.getColumnName(i),rs.getString(i));
ll.add(rowData);
}
}
catch(SQLException e){
System.out.println(e);
}
}
/**
*打印数据
*/
public void printData(){
for(int i=0;i
System.out.println(ll.get(i));
}
}
/**
*插入数据
*/
public void insert(){
try{
//插入语句
String str = "INSERT INTO db.tblStudent(strName,intAge,strAddress,strSex,grandId)"
+"VALUES(?,?,?,?,?)";
pstat = conn.prepareStatement(str);
pstat.setString(1,"王文远");
pstat.setInt(2,20);
pstat.setString(3,"北京");
pstat.setString(4,"T");
pstat.setInt(5,4);
int record = pstat.executeUpdate();
System.out.println("插入"+record+"数据");
}
catch(SQLException e){
System.out.println(e);
}
}
/**
*删除数据
*/
public void delete(){
try{
//删除语句
String str = "DELETE FROM db.tblStudent where strName='王五'";
stat.executeUpdate(str);
}
catch(SQLException e){
System.out.println(e);
}
System.out.println("删除数据成功");
}
/**
*修改数据
*/
public void update(){
try{
//修改语句
String str = "UPDATE db.tblstudent SET strAddress='北京',intAge=intAge+5 where intId=1";
stat.executeUpdate(str);
}
catch(SQLException e){
System.out.println(e);
}
System.out.println("修改数据成功");
}
public static void main(String[] args){
Db2ConnTest dc = new Db2ConnTest();
dc.connDb2();
dc.insert();
//dc.searchData();
//dc.delete();
//dc.update();
dc.searchData();
dc.printData();
dc.closeDb2();
}
}