Java连接PostgreSql数据库及基本使用方式

 更新时间:2023年03月01日 11:01:37   作者:_码农耕地人  
这篇文章主要介绍了Java连接PostgreSql数据库及基本使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

我是应用Java封装的思想将所有的方法封装到了一个类里。

一)准备工作

1.下载链接需要的jar包

选择最新版本即可。

2.下载之后添加到模块里

3.创建一个工具类Util

书写空参构造,用于对数据库的全部操作。

二)连接

所需内容:数据库名,端口号,数据库地址,数据库用户名,密码

public static Connection Connect(){
        Connection c = null;
        try {
 
            Class.forName("org.postgresql.Driver");
            c = DriverManager
                    .getConnection("jdbc:postgresql://服务器地址,本机写127.0.0.1:服务器端口号,默认5432/链接的数据库名",
                            "数据库用户名", "数据库密码");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getClass().getName()+": "+e.getMessage());
            System.exit(0);
        }
        System.out.println("Opened database successfully");
        return c; //记得返回一下这个对象,后面一直在用
    }

三)查询

普通版本查询:数据库有三个字段,时间time、地点location、温度temperature

public static void select() {
        //与数据库建立链接
        Connection c = Util.Connect();
        Statement stmt = null;
        try {
            stmt = c.createStatement();
            String sql = "SELECT* FROM tmps;";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                Date date = rs.getDate(1);
                String location = rs.getString("location");
                float temperature = rs.getFloat("temperature");
                System.out.println("date" + date);
                System.out.println("location:" + location);
                System.out.println("temperature:" + temperature);
            }
            //关流操作
            rs.close();
            stmt.close();
            c.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

下图中这种方法属于进阶方法,只需要输入sql语句即可将任意表中的数据都按照map集合的方式返回

public static List<HashMap<String,Object>> Select(String sql){
        //1、与数据库建立链接
        Connection c = Util.Connect();
        //2、创建操作对象
        Statement stmt = null;
        //3、创建返回最终查询的数据集合
        List<HashMap<String ,Object>> list=new ArrayList<>();
        try {
            //2.1、初始化操作对象
            stmt = c.createStatement();
            //4、执行需要执行的sql语句
            ResultSet rs = stmt.executeQuery(sql);
            //3.1开始封装返回的对象
            ResultSetMetaData metaData = rs.getMetaData();//获取全部列名
            int columnCount = metaData.getColumnCount();//列的数量
            //5、读取数据
            while (rs.next()) {
                HashMap<String,Object> map=new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    //getColumnName获取列名
                    String name = metaData.getColumnName(i);
                    //获取对应的元素
                    Object object = rs.getObject(i);
                    map.put(name,object);
                }
                list.add(map);
            }
            //6、关流操作
            rs.close();
            stmt.close();
            c.close();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return list;
    }

四)添加

返回值是bool类型,表示是否添加成功。

***需要比查询多添加一句***

connect.setAutoCommit(false);
    public static Boolean Insert(String sql){
        //1、与数据库建立链接
        Connection connect = Util.Connect();
        //2、创建操作对象
        Statement stmt = null;
        int count = 0;
        try {
            //2.1、初始化创建对象
            stmt=connect.createStatement();
            //3、添加特殊语句。
            connect.setAutoCommit(false);//之前不用
            //4、执行添加操作
            count = stmt.executeUpdate(sql);
            
            //5、关流
            stmt.close();
            connect.commit();
            connect.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count!=0;
    }

五)删除数据

public void Delete(String sql) {
        //1、链接数据库
        Connection c = this.Connect();
        Statement stmt = null;
        try {
            c.setAutoCommit(false);
            stmt = c.createStatement();
 
            stmt.executeUpdate(sql);
            c.commit();
            c.close()
            stmt.close();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

六)封装之后的代码总和 

封装类

package postSQL.Util;
 
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
public class Util {
    private final Connection connect;
    private final String userName;
    private final String passWord;
    private final String ipAddress;
    private final String databaseName;
    private final String port;
 
    //构造方法
    public Util(String userName, String passWord, String ipAddress, String databaseName, String port) {
        this.userName = userName;
        this.passWord = passWord;
        this.ipAddress = ipAddress;
        this.databaseName = databaseName;
        this.port = port;
        this.connect = this.Connect();
    }
 
    //建立链接
    private Connection Connect() {
        Connection c = null;
        try {
            Class.forName("org.postgresql.Driver");
            c = DriverManager
                    .getConnection("jdbc:postgresql://" + this.ipAddress + ":" + this.port + "/" + this.databaseName,
                            this.userName, this.passWord);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
        return c;
    }
 
    //关流操作
    public void close() {
        Connection c = this.connect;
        try {
            c.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
 
    //查询
    public List<HashMap<String, Object>> Select(String sql) {
        //1、与数据库建立链接
        Connection c = this.connect;
        //2、创建操作对象
        Statement stmt = null;
        //3、创建返回最终查询的数据集合
        List<HashMap<String, Object>> list = new ArrayList<>();
        try {
            //2.1、初始化操作对象
            stmt = c.createStatement();
            //4、执行需要执行的sql语句
            ResultSet rs = stmt.executeQuery(sql);
            //3.1开始封装返回的对象
            ResultSetMetaData metaData = rs.getMetaData();//获取全部列名
            int columnCount = metaData.getColumnCount();//列的数量
            //5、读取数据
            while (rs.next()) {
                HashMap<String, Object> map = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    //getColumnName获取列名
                    String name = metaData.getColumnName(i);
                    //获取对应的元素
                    Object object = rs.getObject(i);
                    map.put(name, object);
                }
                list.add(map);
            }
            //6、关流操作
            rs.close();
            stmt.close();
            //c.close();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return list;
    }
 
    //插入操作
    public Boolean Insert(String sql) {
        //1、与数据库建立链接
        Connection connect = this.connect;
        //2、创建操作对象
        Statement stmt = null;
        int count = 0;
        try {
            //2.1、初始化创建对象
            stmt = connect.createStatement();
            //3、添加特殊语句。
            connect.setAutoCommit(false);//之前不用
            //4、执行添加操作
            count = stmt.executeUpdate(sql);
 
            //5、关流
            stmt.close();
            connect.commit();
            //connect.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count != 0;
    }
 
    //删除
    public void Delete(String sql) {
        //1、链接数据库
        Connection c = this.Connect();
        Statement stmt = null;
        try {
            c.setAutoCommit(false);
            stmt = c.createStatement();
 
            stmt.executeUpdate(sql);
            c.commit();
 
            stmt.close();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }
}

使用测试类

 public static void main(String[] args) {
        //构造方法
        Util util=new Util("用户名","密码",
                "ip地址","数据库名","端口号");
        //插入语法
        Boolean insert = util.Insert("insert into tmps (time,location,temperature)" +
                " values('2022-1-1 16:00:00','场景八',112.3);"); //插入
        //删除
        util.Delete("delete from tmps t where t.location='场景七' "); 
        //查询
        List<HashMap<String, Object>> select = util.Select("select * from tmps");  
        //关流
        util.close();
        System.out.println(select);
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • IDEA编写JavaWeb出现乱码问题解决方案

    IDEA编写JavaWeb出现乱码问题解决方案

    这篇文章主要介绍了IDEA编写JavaWeb出现乱码问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • SpringBoot深入刨析数据层技术

    SpringBoot深入刨析数据层技术

    这篇文章主要介绍了SpringBoot数据层技术的解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • Java实现几十万条数据插入实例教程(30万条数据插入MySQL仅需13秒)

    Java实现几十万条数据插入实例教程(30万条数据插入MySQL仅需13秒)

    这篇文章主要给大家介绍了关于Java如何实现几十万条数据插入的相关资料,30万条数据插入MySQL仅需13秒,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2023-04-04
  • Java性能工具JMeter实现上传与下载脚本编写

    Java性能工具JMeter实现上传与下载脚本编写

    性能测试工作中,文件上传也是经常见的性能压测场景之一,那么 JMeter 文件上传下载脚本怎么做,本文详细的来介绍一下,感兴趣的可以了解一下
    2021-07-07
  • Java算法之堆排序代码示例

    Java算法之堆排序代码示例

    这篇文章主要介绍了Java算法之堆排序代码示例,具有一定参考价值,需要的朋友可以了解下。
    2017-11-11
  • Netty分布式固定长度解码器实现原理剖析

    Netty分布式固定长度解码器实现原理剖析

    这篇文章主要为大家介绍了Netty分布式固定长度解码器原理剖析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-03-03
  • java集合Collection常用方法解读

    java集合Collection常用方法解读

    这篇文章主要介绍了java集合Collection常用方法解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • mybatis 遍历foreach中or拼接的操作

    mybatis 遍历foreach中or拼接的操作

    这篇文章主要介绍了mybatis 遍历foreach中or拼接的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Springboot中加入druid连接池

    Springboot中加入druid连接池

    这篇文章主要介绍了Springboot中加入druid连接池,Druid是目前最好的数据库连接池。在功能、性能、扩展性方面,都超过其他数据库连接池,同时加入了日志监控,下面来看看文章的具体内容吧
    2022-01-01
  • Java泛型映射不同的值类型详解及实例代码

    Java泛型映射不同的值类型详解及实例代码

    这篇文章主要介绍了Java泛型映射不同的值类型详解及实例代码的相关资料,需要的朋友可以参考下
    2017-02-02

最新评论