JDBC-实例1

来源:互联网 发布:芳纶纸淘宝 编辑:程序博客网 时间:2024/05/29 15:08

综合实例(结合上一篇的工具类tools):

/* *@Author swxctx *@time 2016年7月21日 */package base.jdbc;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import com.mysql.jdbc.Connection;public class CRUD {public static void main(String[] args) throws ClassNotFoundException, SQLException {// TODO Auto-generated method stub//create();read();//update();//delete();}//添加数据static void create() throws ClassNotFoundException, SQLException{Connection conn=null;//建立连接Statement st=null;//创建语句ResultSet rs=null;//执行语句try {//Class.forName("com.mysql.jdbc.Driver");//注册驱动conn=tools.getConnection();//建立连接st=conn.createStatement();//建立语句//新增记录String creat="insert into box(box_id,box_state,box_size) values('4','1','4')";int i=st.executeUpdate(creat);if(i==1){System.out.println("Success...");}else{try {System.out.println("Failed...");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}finally{//释放资源tools.free(rs, st, conn);}}//查询数据static void read() throws SQLException, ClassNotFoundException{Connection conn=null;//建立连接Statement st=null;//创建语句ResultSet rs=null;//执行语句try {//Class.forName("com.mysql.jdbc.Driver");//注册驱动conn=tools.getConnection();//建立连接st=conn.createStatement();//建立语句rs=st.executeQuery("select box_id,box_state,box_size from box");//执行语句//处理结果System.out.println("编号\t状态\t型号\t");while(rs.next()){System.out.println(rs.getObject("box_id")+"\t"+rs.getObject("box_state")+"\t"+rs.getObject("box_size")+"\t");}}finally{//释放资源tools.free(rs, st, conn);}}//更新数据static void update() throws ClassNotFoundException, SQLException{Connection conn=null;//建立连接Statement st=null;//创建语句ResultSet rs=null;//执行语句try {//Class.forName("com.mysql.jdbc.Driver");//注册驱动conn=tools.getConnection();//建立连接st=conn.createStatement();//建立语句//新增记录String up="update box set box_id=box_id-10";//int i=st.executeUpdate(creat);int j=st.executeUpdate(up);System.out.println(""+j+"条数据更新...");}finally{//释放资源tools.free(rs, st, conn);}}//删除数据static void delete() throws ClassNotFoundException, SQLException{Connection conn=null;//建立连接Statement st=null;//创建语句ResultSet rs=null;//执行语句try {//Class.forName("com.mysql.jdbc.Driver");//注册驱动conn=tools.getConnection();//建立连接st=conn.createStatement();//建立语句//新增记录String de="delete from box where box_id='4'";//int i=st.executeUpdate(creat);int k=st.executeUpdate(de);System.out.println(""+k+"条数据被删除...");}finally{//释放资源tools.free(rs, st, conn);}}}


0 0