JDBC练习_update、DDL语句和JDBC各个类详解_ResultSet_基本使用
JDBC练习_delete、DDL语句
/* account表 删除一条记录 */ private static void delete() { Connection conn = null; Statement stat = null; try { //注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root"); //定义sql String sql = "delete from account where id = 3"; //获取执行sql的对象 Statement stat = conn.createStatement(); //执行sql int i = stat.executeUpdate(sql); //处理结果 System.out.println(i); if (i>0){ System.out.println("删除成功"); }else { System.out.println("删除失败"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { if (stat!=null){ try { stat.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }


/* 创建一张student表 */ private static void DDL() { Connection conn = null; Statement stat = null; try { //注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root"); //定义sql String sql = "create table student (id int, name varchar(20))"; //获取执行sql的对象 Statement stat = conn.createStatement(); //执行sql int i = stat.executeUpdate(sql); //处理结果 System.out.println(i); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { if (stat!=null){ try { stat.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }


JDBC各个类详解_ResultSet_基本使用
ResultSet:结果集对象,封装查询结果
next() :游标向下移动一行
getXxx(参数):获取数据
Xxx:代表数据类型 如:int getInt(),String getString()
参数:
1.int:代表列的编号,从1开始 如:getString(1)
2.String : 代表列名称。如:getDouble("balance")
private static void ResultSet() { Connection conn = null; Statement stat = null; ResultSet rs = null; try { //注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root"); //定义sql String sql = "select * from account"; //获取执行sql的对象 Statement stat = conn.createStatement(); //执行sql rs = stat.executeQuery(sql); //处理结果 //让游标向上移动一行 rs.next(); //获取数据 int id = rs.getInt(1); String name = rs.getString("name"); double balance = rs.getDouble(3); System.out.println(id+"-"+name+"-"+balance); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { if (rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (stat!=null){ try { stat.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }


浙公网安备 33010602011771号