java简单数据库操作

连接

  public Connection con;
  public Statement statement;
  //驱动程序名
  public String driver = "com.mysql.jdbc.Driver";
  //URL指向要访问的数据库名mydata
  public String url = "jdbc:mysql://localhost:3306/mydata";
  //MySQL配置时的用户名
  public String user = "root";
  //MySQL配置时的密码
  public String password = "root";
  try {
      //加载驱动程序
        Class.forName(driver);
        //连接MySQL数据库!!
        con = DriverManager.getConnection(url,user,password);
        if(!con.isClosed())
            statement = con.createStatement();
        else
            System.out.println("连接失败");
    }catch(ClassNotFoundException e) {
        e.printStackTrace();
    } catch(SQLException e) {
        e.printStackTrace();
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();  
    }finally{
        System.out.println("连接成功");
    }  

增加(insert)/修改(update)/删除(delete)

  String sqlStr = "UPDATE stutable SET name='名字' WHERE ID = '30'";
  //sqlStr = "INSERT INTO stutable (name,age) VALUES ('名字','25')";
  //sqlStr = "DELETE FROM stutable WHERE ID = '30'";
  int rs = 0;
  try {
        rs = statement.executeUpdate(sqlStr);
        if(rs == 1){ 
             System.out.println("操作成功"); 
        }else{
              System.out.println("操作失败"); 
        }
    
      } catch (SQLException e) {
          e.printStackTrace();
      }  

查询(selete)

    String sqlStr = "SELECT * FROM stutable WHERE ID = '30'";  
    ResultSet rs = null;  
    try {  
        rs = statement.executeQuery(sqlStr);  
        if(rs.next()){  //while(rs.next())  
           String str_ID   = rs.getString("ID");    
           String str_name = rs.getString("name");    
           String str_age  = rs.getString("age");  
        }else {  
            System.out.print("不存在");  
        }  
    } catch (SQLException e) {  
        e.printStackTrace();  
    }finally {  
    }  

转载于:https://my.oschina.net/u/3697586/blog/1543638

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值