java基础之JDBC二:基础应用
时间:2022-03-15 08:49
JDBC的基础应用CURD:
增删改
public void noQuery() { Connection conn = null; Statement stat = null; try { //注册驱动 Class.forName("com.mysql.jdbc.Driver"); //获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///tempDb", "root", "123"); stat = conn.createStatement(); String sql = "---";
//执行 int num = stat.executeUpdate(sql); if(num > 0) { System.out.println("操作成功"); } else { System.out.println("操作失败"); } //释放资源 stat.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } }
查询
public static void query() { Connection conn = null; Statement stat = null; try { //注册驱动 Class.forName("com.mysql.jdbc.Driver"); //获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///tempDb", "root", "123"); stat = conn.createStatement(); String sql = "select * from users"; //执行 ResultSet rs = stat.executeQuery(sql); while (rs.next()) { int id = rs.getInt("uid"); String name = rs.getString("uname"); String psw = rs.getString("psw"); System.out.println(id + "--" + name + "--" + psw); } //释放资源 rs.close(); stat.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } }