代码:
public class Text {
public static void main(String[] args) {
Connection con;
PreparedStatement pst ;
ResultSet rs =null;
try {
// 获取链接
con = JDBCUtil.getConnection();
String sql = "SELECT * FROM book WHERE id = ?";
pst = con.prepareStatement(sql);
//添加:
String insert="INSERT INTO book VALUES(5,'HarryPotter',45)";
Object[] params={2,"HarryPotter"};
int i=JDBCUtil.update(con,insert,params,rs,pst);
if (i==0)
{
System.out.println("添加失败!");
}
else {
System.out.println("添加成功!");
}
System.out.println("查询:");
System.out.println("“序号"+"\t\t"+"书名"+"\t\t"+"价格");
rs = JDBCUtil.query(con, pst, rs, sql, params);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int price = rs.getInt("price");
System.out.println(id + "\t\t" + name + "\t\t" + price);
}
System.out.println("----------------------");
//删除:
String delete="DELETE FROM book WHERE id = 4";
Object[] params1={2,"物理"};
i=JDBCUtil.update(con,delete,params1,rs, pst);
if (i==0)
{
System.out.println("删除失败!");
}
else {
System.out.println("删除成功!");
}
System.out.println("查询:");
System.out.println("“序号"+"\t\t"+"书名"+"\t\t"+"价格");
rs = JDBCUtil.query(con, pst, rs, sql, params1);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int price = rs.getInt("price");
System.out.println(id + "\t\t" + name + "\t\t" + price);
}
System.out.println("----------------------");
//更改:
System.out.println("查询:");
System.out.println("序号"+"\t\t"+"书名"+"\t\t"+"价格");
Object[] params2={2,"语文"};
rs = JDBCUtil.query(con, pst, rs, sql, params2);
while (rs.next())
{
System.out.println(rs.getInt("id")+"\t\t"+rs.getString("name")+"\t\t"+rs.getInt("price"));
}
String set="UPDATE book SET price=1 WHERE id=1";
i=JDBCUtil.update(con,set,params2,rs, pst);
if (i==0)
{
System.out.println("更改失败!");
}
else
{
System.out.println("更改成功!");
}
System.out.println("查询:");
System.out.println("序号"+"\t\t"+"书名"+"\t\t"+"价格");
Object[] params5={2,"语文"};
rs = JDBCUtil.query(con, pst, rs, sql, params2);
while (rs.next())
{
System.out.println(rs.getInt("id")+"\t\t"+rs.getString("name")+"\t\t"+rs.getInt("price"));
}
// 关闭数据库
JDBCUtil.release(con, pst, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
运行结果:
表book: