postgresql JDBC操作数据库

先下载驱动:

org.postgresql
postgresql
42.2.6

package postgresql;

import java.sql.*;

public class TestPostreSQL {
public static void main(String args[]) throws Exception{
//executeSQL(“create table t_demo(id int,name varchar(32),address varchar(128))”);
//executeSQL(“insert into t_demo values(1,‘atlas’,‘深圳’)”);
//executeSQL(“update t_demo set address=‘广州’ where id=1”);
//executeSQL(“delete from t_demo where id=1”);
queryData();

}

public static void queryData() throws Exception{
    Connection connection = null;
    try{
        connection = getConnection();
        connection.setAutoCommit(true);
        String querySQL="select * from t_demo";
        PreparedStatement pstmt = connection.prepareStatement(querySQL);
        ResultSet rs = pstmt.executeQuery();
        while(rs.next()){
            int id = rs.getInt(1);
            String name = rs.getString(2);
            String address = rs.getString(3);
            System.out.println("id:"+id+"  name:"+name+"  address:"+address);
        }

    }catch(Exception e){
        e.printStackTrace();
    }finally {
        if(null != connection){
            connection.close();
            connection =  null;
        }
    }
}

public static void executeSQL(String strSQL) throws Exception{
    Connection connection = null;
    try{
        connection = getConnection();
        connection.setAutoCommit(true);
        Statement stmt = connection.createStatement();
        stmt.execute(strSQL);
    }catch(Exception e){
        e.printStackTrace();
    }finally {
        if(null != connection){
            connection.close();
            connection =  null;
        }
    }
}


public static Connection getConnection() throws SQLException{
    String url = "jdbc:postgresql://10.11.11.110:5432/atlas";
    String driverClass = "org.postgresql.Driver";
    try{
        Class.forName(driverClass);
    }catch(ClassNotFoundException e){
        throw new SQLException(driverClass+"not found!");
    }
    Connection connection = DriverManager.getConnection(url,"atlas","atlas");
    return  connection;
}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值