1.数据库部分
创建数据表customer(客户)、deposite(存款)、bank(银行),表结构如下:
2.Java部分
importjava.io.*;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.util.*;
publicclassTestBank {
publicstaticvoidmain(Stringargs[]) {
//getConn();
//insertBank();
//selectCustomer();
//delete();
update();
}
privatestaticConnection getConn() {
String driver= "com.mysql.jdbc.Driver";
String url= "jdbc:mysql://localhost:3306/bank";
String username= "root";
String password= "root";
Connection conn=null;
try{
Class.forName(driver);//classLoader,加载对应驱动
conn= (Connection) DriverManager.getConnection(url,username,password);
System.out.println("SUCCED");
}catch(ClassNotFoundExceptione) {
e.printStackTrace();
}catch(SQLExceptione) {
e.printStackTrace();
}
returnconn;
}
privatestaticintinsertBank(){
Connection conn=getConn();
inti= 0;
String sql= "insert into bank (b_id,bank_name) values(?,?)";
PreparedStatement pstmt;
try{
pstmt= (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1,"A0005");
pstmt.setString(2,"石嘴山银行");
i= pstmt.executeUpdate();
System.out.println("插入了: "+i+"条!");
pstmt.close();
conn.close();
}catch(SQLExceptione) {
e.printStackTrace();
}
returni;
}
privatestaticStringselectCustomer(){
Connection conn=getConn();
String sql= "select * from customer";
PreparedStatement pstmt;
try{
pstmt= (PreparedStatement)conn.prepareStatement(sql);
ResultSet rs= pstmt.executeQuery();
intcol=rs.getMetaData().getColumnCount();
System.out.println("============================");
while(rs.next()) {
for(inti= 1;i<=col; i++) {
System.out.print(rs.getString(i) +"\t");
if((i== 2) && (rs.getString(i).length() < 8)) {
System.out.print("\t");
}
}
System.out.println("");
}
System.out.println("============================");
pstmt.close();
conn.close();
}catch(SQLExceptione) {
e.printStackTrace();
}
returnnull;
}
//delete
privatestaticintdelete(){
Connection conn=getConn();
inti= 0;//统计条数
String sql= "delete from bank where b_id='A0005'";
PreparedStatement pstmt;
try{
pstmt= (PreparedStatement) conn.prepareStatement(sql);
i= pstmt.executeUpdate();
System.out.println("删除了: "+i+"条!"+"删除语句为:"+sql);
pstmt.close();
conn.close();
}catch(SQLExceptione) {
e.printStackTrace();
}
returni;
}
//更新customer的数据
privatestaticintupdate() {
Connection conn=getConn();
inti= 0;
String sql= "update customer set salary='121452.00' where c_id='101004'";
PreparedStatement pstmt;
try{
pstmt= (PreparedStatement) conn.prepareStatement(sql);
i= pstmt.executeUpdate();
System.out.println("更新了"+i+"条!"+"更新语句为:"+sql);
pstmt.close();
conn.close();
}catch(SQLExceptione) {
e.printStackTrace();
}
returni;
}
}