时间:2021-07-01 10:21:17 帮助过:14人阅读
增加数据:
1 public static void add(Connection conn,Statement stat,ResultSet rs){ 2 try { 3 //注册mysql驱动 4 Class.forName("com.mysql.jdbc.Driver"); 5 //建立连接 6 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1","root","admin"); 7 //创建传输器 8 stat = conn.createStatement(); 9 //操作数据 10 int rows = stat.executeUpdate("insert into account values(null,‘张三‘,88888888)"); 11 System.out.println("添加了"+rows+"条"); 12 } catch (Exception e) { 13 e.printStackTrace(); 14 }finally{ 15 JDBCutils.closeResou(conn, stat,rs); 16 } 17 }
查看数据:
1 public static void check(Connection conn,Statement stat,ResultSet rs){ 2 3 try { 4 //注册mysql驱动 5 Class.forName("com.mysql.jdbc.Driver"); 6 //建立连接 7 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1","root","admin"); 8 //创建传输器 9 stat = conn.createStatement(); 10 //操作数据 11 rs = stat.executeQuery("select name 名字 from account where money = 500;"); 12 while(rs.next()){ 13 System.out.println(rs.getString("名字")); 14 } 15 16 } catch (SQLException e) { 17 e.printStackTrace(); 18 }finally{ 19 JDBCutils.closeResou(conn, stat, rs); 20 } 21 22 }
PreparedStatement对数据的增删查改:
增加数据:
public static void add(Connection conn,PreparedStatement ps){ //注册驱动 try { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql:///mydb1","root","admin"); String sql = "insert into account values(null,?,?) "; ps = conn.prepareStatement(sql); ps.setString(1, "李达康"); ps.setDouble(2, 1000); int rows = ps.executeUpdate(); System.out.println("添加了:"+rows); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); }finally{ JDBCutils.closeResou(conn, ps, null); } }
删除数据:
public static void del(Connection conn,PreparedStatement ps){ try { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql:///mydb1","root","admin"); String sql="delete from account where id=?"; ps = conn.prepareStatement(sql); ps.setInt(1, 10); int rows = ps.executeUpdate(); System.out.println("删除了"+rows); } catch (Exception e) { e.printStackTrace(); }finally{ JDBCutils.closeResou(conn, ps, null); } }
查数据:
public static void check(Connection conn,PreparedStatement ps,ResultSet rs){ try { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql:///mydb1","root","admin"); String sql="select id from account where name=?"; ps = conn.prepareStatement(sql); ps.setString(1,"童旭平"); rs = ps.executeQuery(); while(rs.next()){ System.out.println(rs.getInt("id")); } } catch (Exception e) { e.printStackTrace(); }finally{ JDBCutils.closeResou(conn, ps, rs); } }
JDBC基本知识
标签:into cat 获取数据 cti trace 优点 ace 取数 set