JDBC:Java连接Phoenix代码

package com.fcf;
import java.sql.*;
public class App {
    public static Connection connection;
    public static PreparedStatement ps;
    public static ResultSet resultSet;
    public static void main( String[] args ) throws SQLException, ClassNotFoundException {
        init();
        //createTable();
        addData();
        //deleteData();
        //searchData();
        closeAll();
    }
    //JDBC的开发流程
    //创建连接对象
    public static void init() throws ClassNotFoundException, SQLException {
        //加载驱动类
        Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
        //编写连接字符串
        String url="jdbc:phoenix:master:2181/hbase";
        connection=DriverManager.getConnection(url);
        System.out.println("连接成功!");
    }
    //关闭资源
    public static void closeAll() throws SQLException {
        if (resultSet!=null){
            resultSet.close();
        }
        if (ps!=null){
            ps.close();
        }
        if (connection!=null){
            connection.close();
        }
    }
    //创建表
    public static void createTable() throws SQLException {
        String sql="create table DOG(ID bigint primary key,NAME varchar)";
        ps=connection.prepareStatement(sql);
        int i=ps.executeUpdate();
        connection.commit();
        if (i==0){
            System.out.println("表创建成功!");
        }
    }
    //向表中存入数据
    public static void addData() throws SQLException {
        String sql="upsert into DOG values(?,?)";
        ps=connection.prepareStatement(sql);
        ps.setInt(1,001);
        ps.setString(2,"DaHuang");
        int i=ps.executeUpdate();
        //提交事务
        connection.commit();
        if (i>0){
            System.out.println("数据插入成功!");
        }
    }
    //删除数据
    public static void deleteData() throws SQLException {
        String sql="delete from US_POP where CITY=?";
        ps=connection.prepareStatement(sql);
        ps.setString(1,"New York");
        int i = ps.executeUpdate();
        connection.commit();
        if (i>0){
            System.out.println("数据删除成功!");
        }
    }
    //查看数据
    public static void searchData() throws SQLException {
        String sql="select * from US_POP where POPULATION>=?";
        ps=connection.prepareStatement(sql);
        ps.setInt(1,2000000);
        ResultSet resultSet = ps.executeQuery();
        while (resultSet.next()){
            System.out.print("国家名称:"+resultSet.getString("STATE"));
            System.out.print(";\t城市:"+resultSet.getString("CITY"));
            System.out.print(";\t人口:"+resultSet.getInt("POPULATION"));
            System.out.println();
        }
    }
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值