直接上下代码:
package com.learn.jdbc.chap04.sec02; import java.sql.Connection;
import java.sql.PreparedStatement; import com.learn.jdbc.model.Album;
import com.learn.jdbc.util.DbUtil;
/**
* 使用PreparedStatement接口实现增删改操作
* @author Administrator
*
*/
public class Demo1 { private static DbUtil dbUtil=new DbUtil();
/**
* 使用PreparedStatement 预编译 添加数据
* @param ab
* @return
* @throws Exception
*/
private static int addAlbum(Album ab) throws Exception{
Connection con=dbUtil.getCon(); // 获取连接
String sql="insert into sp_album values (null,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1,ab.getName());
pstmt.setInt(2,ab.getUid());
pstmt.setLong(3,ab.getTime());
int result = pstmt.executeUpdate();
dbUtil.close(pstmt, con);
return result;
} public static void main(String[] args) throws Exception {
int result = addAlbum(new Album("亲王", 6, System.currentTimeMillis()));
if(result>0){
System.out.println("数据插入成功!");
}else{
System.out.println("数据插入失败!");
}
}
}
package com.learn.jdbc.chap04.sec02; import java.sql.Connection;
import java.sql.PreparedStatement; import com.learn.jdbc.model.Album;
import com.learn.jdbc.util.DbUtil;
/**
* 使用PreparedStatement接口实现增删改操作
* @author Administrator
*
*/
public class Demo2 {
private static DbUtil dbUtil=new DbUtil();
/**
* 使用PreparedStatement 预编译 修改数据
* @param ab
* @return
* @throws Exception
*/
private static int updateAlbum(Album ab) throws Exception{
Connection con=dbUtil.getCon(); // 获取连接
String sql="update sp_album set name=?,uid=?,add_time=? where id=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1,ab.getName());
pstmt.setInt(2,ab.getUid());
pstmt.setLong(3,ab.getTime());
pstmt.setInt(4,ab.getId());
int result = pstmt.executeUpdate();
dbUtil.close(pstmt, con);
return result;
} public static void main(String[] args) throws Exception {
int result = updateAlbum(new Album(9,"亲王66", 8, System.currentTimeMillis()));
if(result>0){
System.out.println("数据修改成功!");
}else{
System.out.println("数据修改失败!");
}
}
}
package com.learn.jdbc.chap04.sec02; import java.sql.Connection;
import java.sql.PreparedStatement; import com.learn.jdbc.util.DbUtil;
/**
* 使用PreparedStatement接口实现增删改操作
* @author Administrator
*
*/
public class Demo3 {
private static DbUtil dbUtil=new DbUtil(); /**
* 使用PreparedStatement 预编译 删除数据
* @param ab
* @return
* @throws Exception
*/
private static int deleteAlbum(int id) throws Exception{
Connection con=dbUtil.getCon(); // 获取连接
String sql="delete from sp_album where id=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1,id);
int result = pstmt.executeUpdate();
dbUtil.close(pstmt, con);
return result;
} public static void main(String[] args) throws Exception{
int result = deleteAlbum(15);
if(result>0){
System.out.println("数据删除成功!");
}else{
System.out.println("数据删除失败!");
}
}
}