package cn.itcaast.jdbc; import java.sql.*; /* * * */ public class jbdc_insert { public static void main(String[] args) { Connection conn=null; Statement stmt=null; try{ //1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2.定义sql String sql="insert into account values(null,'wangwu',3000)"; //3.获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql:///saob1", "root", "root"); //4.获取执行sql的对象statement stmt = conn.createStatement(); //5.执行sql int count = stmt.executeUpdate(sql); //6.处理结果 System.out.println(count); if(count>0){ System.out.println("添加成功"); }else{ System.out.println("添加成功"); } }catch(ClassNotFoundException e){ e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //先释放stat,因为它是由conn获取的,先释放后来者。 //stmt.close();//如果密码输入错误,nameconn那一步就会报错, // 直接跳过stmt到catch,就会报空指针异常;先判断stmt!=null再释放他 if (stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }//psvm }
jdbk简单入门示例程序的对于异常的处理示例
最新推荐文章于 2024-10-11 21:07:49 发布