package cn.code.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.junit.Test; public class NumberThree { /** * 使用jdbc完成对数据库的增删改查 * */ @Test public void update(){ //url遵循jdbc协议,每种数据库的url各有不同 /** * jdbc:sqlserver://IP地址:1433;DatabaseName=库名 * jdbc:oracle:thin:@IP地址:1521:库名 * */ String url="jdbc:mysql://localhost:3306/mydb1"; String user = "root"; String password="123"; String driverclassname="com.mysql.jdbc.Driver"; Connection con =null; Statement statement=null; ResultSet r=null; try { Class.forName(driverclassname); try { con = DriverManager.getConnection(url, user, password); statement=con.createStatement(); //String sql ="update stu set name='zhoujielun',age='37',gender='male' where number='itcast_0002'"; String sql="insert into stu values('itcast_0980','diaosi','76','male')"; //String sql ="delete from stu where number='itcast_0980'"; int c = statement.executeUpdate(sql);//返回值为影响的行数 System.out.println(c); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //查询 @Test public void query(){ String url="jdbc:mysql://localhost:3306/mydb1"; String driverclassname="com.mysql.jdbc.Driver"; String user ="root"; String password="123"; Connection con=null; Statement statement=null; ResultSet resultSet=null; try { Class.forName(driverclassname); try { con=DriverManager.getConnection(url, user, password); statement = con.createStatement(); String sql="select * from stu"; //必须是查询语句 resultSet = statement.executeQuery(sql); /** * 解析resultset * resultset内有一个光标,默认位置beforeFirst(这是一个空位置) * 通过ResultSet的next()方法可以把光标向下移动一行,第一次调用到first行 * 最后一行是afterLast,最后有效行Last; * */ while(resultSet.next()){ /** * ResultSet提供了一系列的getXxx()方法 * getInt(第几列)/getInt("列名") * getString()同上 * getDouble()同上 * getTime()同上 * getObject()同上 * */ String number = resultSet.getString(1); String name=resultSet.getString("name"); int age = resultSet.getInt("age"); String gender = resultSet.getString(4); System.out.println("number="+number+"-name="+name+"-age="+age+"-gender="+gender); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { if(resultSet!=null)resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(statement!=null)statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(con!=null)con.close();//必须关 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }