开发者

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

目录
  • 一)准备工作
    • 1.下载链接需要的jar包
    • 2.下载之后添加到模块里
    • 3.创建一个工具类Util
  • 二)连接
    • 三)查询
      • 四)添加
        • 五)删除数据
          • 六)封装之后的代码总和 
            • 封装类
            • 使用测试类
          • 总结

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

            一)准备工作

            1.下载链接需要的jar包

            选择最新版本即可。

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

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

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

            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 {
                        sphptmt = 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 (rwww.devze.coms.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(Stri开发者_开发培训ng 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);
                }

            总结

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

            0

            上一篇:

            下一篇:

            精彩评论

            暂无评论...
            验证码 换一张
            取 消

            最新开发

            开发排行榜