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();
}
}
}
JDBC:Java连接Phoenix代码
最新推荐文章于 2022-01-30 16:22:30 发布