休息10天后重新看了下jdbc,开始振作继续学习(休息10天主要是因为驾照考试太累,2333),希望自己能够调整好心态,继续对程序有着一如既往的喜爱(加油)
Connection con=null; Statement sm=null; try { //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.创建链接 con=DriverManager.getConnection("jdbc:mysql://localhost:3306/testkeyandforeigh", "root", "123456"); //3.创建statement或者preparedStatement【区别】 //主要用于发送sql语句 sm=con.createStatement(); //4.执行(srud操作,或者创建删除数据库等) String sql="insert into category(cname) values ('socks')"; int rs=sm.executeUpdate(sql);//注意rs是返回值,返回的是更新的数量,更新一条数据返回1,2条数据返回2,删除失败应该返回0,删除成功返回1 if(rs==1) { System.out.println("添加成功"); } else { System.out.println("添加失败"); } } catch (Exception e) { e.printStackTrace(); }finally { //关闭资源 try { if (sm!=null) sm.close(); if (con!=null) con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
代码截图如上