JDBC连接数据库的安全性连接方法
PreparedStatement ps=null; ResultSet rs=null; Connection ct=null; try { Class.forName("com.mysql.jdbc.Driver"); ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/testkeyandforeigh", "root", "123456"); ps=ct.prepareStatement("select * from category where cid>? and cid<?"); ps.setInt(1, 2);//第一个参数是问号的个数,第二个参数是问号的赋值 ps.setInt(2, 8); rs=ps.executeQuery(); while(rs.next()) { System.out.println(rs.getString(1)+'\t'+rs.getString(2)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (ps!=null) ps.close(); if (ct!=null) ct.close(); } catch (SQLException e) { e.printStackTrace(); } }
增删改都用executeUpdate返回的是int(改变了int条的数据),查询用executeQuery(返回是结果集,可用迭代的方法写出来)