对数据库进行增删改操作的步骤:
1.通过Connection对象创建Statement,Statement的功能是向数据库发送SQL语句。
2.通过调用int executeUpdate(String sql),它可以发送DML和DDL
实例:
Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager .getConnection("jdbc:mysql://localhost:3306/sss","LZT","123456"); Statement stmt = con.createStatement(); String sql = "INSERT INTO aaa VALUES(8,'李斯','987654321')"; int r = stmt.executeUpdate(sql); System.out.println(r); stmt.close(); con.close();上面的代码可以往数据表aaa中插入一行内容。
注:增删改的操作步骤相似,只需要修改sql语句即可完成不同的操作。
查询操作
查询操作不同于增删改操作,因为它会返回一个列表,我们需要对列表进行解析。
查询操作具体步骤:
1.通过Connection对象创建Statement,Statement的功能是向数据库发送SQL语句。
2.通过调用ResultSet executeQuery(String seletesql),该函数的参数必须是查询语句。
3.获得了ResultSet对象后可以通过移动行光标移动到每一行之前(next()函数),再通过getInt(列号),getInt(属性名),getString,getDouble等等。
具体实例:
ResultSet set = null; Connection con = null; Statement stmt = null; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager .getConnection("jdbc:mysql://localhost:3306/sss","LZT","123456"); stmt = con.createStatement(); String sql = "select * from aaa"; set = stmt.executeQuery(sql); while(set.next()){//移动行光标 int id = set.getInt("id"); String name = set.getString(2); String phone = set.getString("phone"); System.out.println(id+","+name+","+phone); } }catch(Exception e){ e.printStackTrace(); }finally{ //倒关,先得到的对象迟关 if(set != null)set.close(); if(stmt != null)stmt.close(); if(con != null)con.close(); }注意:
ResultSet对象获取的表格只可以对行光标进行移动,不能对列光标进行操作。该表的内容的第一行称为first,属性行称为beforefirst,最后一行称为last,最后一行之后称为afterlast。
