Java中使用JDBC操作Postgresql
创始人
2024-03-01 00:34:37
0

目录

在Rocky Linux上安装postgresql

用IntelliJ创建JavaFx项目

画一个表格

 建立数据库访问


在Rocky Linux上安装postgresql

Rocky的仓库中自带了postgresql安装包,我们直接用dnf安装即可:

dnf install postgresql-server -y

 安装好之后,先切换到postgres账户,进行初始化:

su postgres
initdb -D /var/lib/pgsql/dataexit

再启用并运行后台服务:

systemctl enable postgresql

systemctl start postgresql

然后安装httpd:

dnf install httpd -y

然后安装PgAdmin,先更新仓库

sudo rpm -i https://ftp.postgresql.org/pub/pgadmin/pgadmin4/yum/pgadmin4-redhat-repo-2-1.noarch.rpm

 然后开始安装:

sudo yum install pgadmin4-web -y

然后启动以下命令进行初始化设置:

sudo /usr/pgadmin4/bin/setup-web.sh 

 启用并运行httpd:

systemctl enable httpd

systemctl start httpd

 排除防火墙:

firewall-cmd --add-service http --permanent

重新加载防火墙配置:

 firewall-cmd --reload

重新启动httpd:

systemctl restart httpd

通过浏览器 打开pgadmin:

 输入之前初始化时填的账号密码进入系统,Server节点上右键:

 选择Register->Server:

 然后右击Database选择Create->Database:

 创建一个shop的库:

 创建表:

CREATE TABLE public.product
(id uuid,product_name character varying(100) NOT NULL,amount integer NOT NULL,unit_price double precision NOT NULL DEFAULT 0,unit_name character varying(10) NOT NULL,PRIMARY KEY (id)
);ALTER TABLE IF EXISTS public.productOWNER to postgres;

用IntelliJ创建JavaFx项目

1. 创建Maven 项目

选择 File -> New -> Project -> JavaFx ,填好后点击OK。

 2. 验证项目

生成的pom文件:


4.0.0com.exampledemo1.0-SNAPSHOTdemoUTF-85.8.2org.openjfxjavafx-controls17.0.2org.openjfxjavafx-fxml17.0.2org.junit.jupiterjunit-jupiter-api${junit.version}testorg.junit.jupiterjunit-jupiter-engine${junit.version}testorg.apache.maven.pluginsmaven-compiler-plugin3.10.11717org.openjfxjavafx-maven-plugin0.0.8default-clicom.example.demo/com.example.demo.HelloApplicationappappapptruetruetrue

3. 运行项目

快捷键Atl+Shift+X,运行。

画一个表格

删掉自动生成的代码,新建Product.java

注意:需要安装lombok插件。

package org.example;import lombok.Data;@Data
public class Product {private String productName;private Double price;private Integer amount;private String unitName;
}

新增Main.java

package org.example;import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;import java.util.ArrayList;
import java.util.List;public class Main extends Application {public static void main(String[] args) {launch(args);}@Overridepublic void start(Stage stage) throws Exception {VBox root = new VBox();Scene scene = new Scene(root, 800, 600);var table = createTable();root.getChildren().add(table);ObservableList products = FXCollections.observableArrayList(queryProducts());table.setItems(products);HBox buttons = new HBox();root.getChildren().add(buttons);Button addButton = new Button("Add");buttons.getChildren().add(addButton);Button delButton = new Button("Delete");buttons.getChildren().add(delButton);stage.setTitle("JAVA商店");stage.setScene(scene);stage.show();}private List queryProducts() {List list = new ArrayList<>();Product p = new Product();p.setProductName("电脑");p.setAmount(10);p.setPrice(3500.0);p.setUnitName("台");list.add(p);p = new Product();p.setProductName("石油");p.setAmount(10);p.setPrice(700.0);p.setUnitName("桶");list.add(p);return list;}private TableView createTable() {TableView tableView = new TableView<>();var col = new TableColumn("名称");col.setCellValueFactory(new PropertyValueFactory("productName"));tableView.getColumns().add(col);var col1 = new TableColumn("数量");col1.setCellValueFactory(new PropertyValueFactory("amount"));tableView.getColumns().add(col1);var col2 = new TableColumn("单价");col2.setCellValueFactory(new PropertyValueFactory<>("price"));tableView.getColumns().add(col2);var col3 = new TableColumn("单位");col3.setCellValueFactory(new PropertyValueFactory<>("unitName"));tableView.getColumns().add(col3);return tableView;}
}

修改pom文件

4.0.0java-demoroot0.0.1-SNAPSHOTjdbcorg.openjfxjavafx-base19org.openjfxjavafx-controls19org.openjfxjavafx-graphics19org.openjfxjavafx-fxml19org.openjfxjavafx-media19org.openjfxjavafx-maven-plugin0.0.8org.example.Main

运行结果:

 建立数据库访问

修改pom.xml添加postgresql的驱动:

org.postgresqlpostgresql42.5.1

修改Main.java,连接数据库:

JDBC4.0之后DriverManager会自动搜索classpath中的驱动类,所以不需要Class.forName('driverClass')的方式加载驱动类。

    private Connection getConnection() throws SQLException {Connection conn = null;Properties connectionProps = new Properties();connectionProps.put("user", "postgres");connectionProps.put("password", "postgres");conn = DriverManager.getConnection("jdbc:postgresql://192.168.0.128/shop",connectionProps);return conn;}

连接到数据库之后,就可以增删改查操作了。为了防止SQL注入,通常查询字符串使用参数化方式,待输入值在查询语句使用“?”代替。

新增:

try {Connection conn = getConnection();String query = "INSERT INTO product(\n" +"\tid, product_name, amount, unit_price, unit_name)\n" +"\tVALUES (?, ?, ?, ?, ?);";try (PreparedStatement stmt = conn.prepareStatement(query)) {stmt.setObject(1, UUID.randomUUID());stmt.setString(2, pn.getText());stmt.setInt(3, Integer.valueOf(amountField.getText()));stmt.setDouble(4, Double.valueOf(priceField.getText()));stmt.setString(5, unitField.getText());stmt.executeUpdate();}conn.close();

最终效果

 

相关内容

热门资讯

喜欢穿一身黑的男生性格(喜欢穿... 今天百科达人给各位分享喜欢穿一身黑的男生性格的知识,其中也会对喜欢穿一身黑衣服的男人人好相处吗进行解...
发春是什么意思(思春和发春是什... 本篇文章极速百科给大家谈谈发春是什么意思,以及思春和发春是什么意思对应的知识点,希望对各位有所帮助,...
网络用语zl是什么意思(zl是... 今天给各位分享网络用语zl是什么意思的知识,其中也会对zl是啥意思是什么网络用语进行解释,如果能碰巧...
为什么酷狗音乐自己唱的歌不能下... 本篇文章极速百科小编给大家谈谈为什么酷狗音乐自己唱的歌不能下载到本地?,以及为什么酷狗下载的歌曲不是...
家里可以做假山养金鱼吗(假山能... 今天百科达人给各位分享家里可以做假山养金鱼吗的知识,其中也会对假山能放鱼缸里吗进行解释,如果能碰巧解...
华为下载未安装的文件去哪找(华... 今天百科达人给各位分享华为下载未安装的文件去哪找的知识,其中也会对华为下载未安装的文件去哪找到进行解...
四分五裂是什么生肖什么动物(四... 本篇文章极速百科小编给大家谈谈四分五裂是什么生肖什么动物,以及四分五裂打一生肖是什么对应的知识点,希...
怎么往应用助手里添加应用(应用... 今天百科达人给各位分享怎么往应用助手里添加应用的知识,其中也会对应用助手怎么添加微信进行解释,如果能...
苏州离哪个飞机场近(苏州离哪个... 本篇文章极速百科小编给大家谈谈苏州离哪个飞机场近,以及苏州离哪个飞机场近点对应的知识点,希望对各位有...
客厅放八骏马摆件可以吗(家里摆... 今天给各位分享客厅放八骏马摆件可以吗的知识,其中也会对家里摆八骏马摆件好吗进行解释,如果能碰巧解决你...