JDBC

JDBC的连接:


  String driverClassName = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/mytb";
  String username = "root";
  String password = "123";
  Class.forName(driverClassName);
  Connection con = DriverManager.getConnection(url, username, password);
  //System.out.println(con);

       1、JDBC的增删改:

  Statement sta = con.createStatement();
  String sql = "insert into stu values('xiaohong','woman',22,'0010')";
  int r = sta.executeUpdate(sql);

       2、JDBC的查寻:

    Statement sta = con.createStatement();
   ResultSet res = sta.executeQuery("select * from emp");
   while(res.next()){
   int empno = res.getInt(1);  //得到表的内容
   String ename = res.getString("ename");
   String job = res.getString("job");
   int mg = res.getInt("mgr");
   Date hiredate = res.getDate("hiredate");
   double sal = res.getDouble("sal");
   double COMM = res.getDouble("COMM");
   int deptno = res.getInt("deptno");
   System.out.println(""+empno+" , "+ename+" , "+job+" , "+mg+" , "+hiredate+" , "+sal+" , "+COMM+" , "+deptno);
  }

  
       3、JDBC的关闭:
                              sta.close();
                              con.close();


规范样式:

 @Test
 public void fun() throws Exception {
  Connection con = null;
  Statement sta = null;
  ResultSet res = null;
  try {
   String driverClassName = "com.mysql.jdbc.Driver";
   String url = "jdbc:mysql://localhost:3306/mytb";
   String username = "root";
   String password = "123";
   Class.forName(driverClassName);
   con = DriverManager.getConnection(url, username, password);

   sta = con.createStatement();
   String sql = "select * from stu";
   res = sta.executeQuery(sql);
   while (res.next()) {
    System.out.println(res.getObject(1) + "  " + res.getObject(2)
      + "  " + res.getObject(3) + "  " + res.getObject(4));
   }
  } catch (Exception e) {
   throw new RuntimeException(e);
  } finally {
   if (res != null)
    res.close();
   if (sta != null)
    sta.close();
   if (con != null)
    con.close();
  }
 }


PreparedStatement:
 @Test
 public void fun2() throws ClassNotFoundException, SQLException{
  String driverClassName = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/mytb";
  String username = "root";
  String password = "123";
  Class.forName(driverClassName);
  Connection con = DriverManager.getConnection(url, username, password);
  
  
  String sql = "select * from emp where ename = ?";
  PreparedStatement pstmt = con.prepareStatement(sql);
  pstmt.setString(1, "甘宁");
  ResultSet rs = pstmt.executeQuery();
  if(rs.next())
  System.out.println(rs.getObject(5));
  rs.close();
  pstmt.close();
  con.close();
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值