Java中使用JDBC操作Postgresql

目录

在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.product
    OWNER to postgres;

用IntelliJ创建JavaFx项目

1. 创建Maven 项目

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

 2. 验证项目

生成的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>demo</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>5.8.2</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>17.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>17.0.2</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.10.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.8</version>
                <executions>
                    <execution>
                        <!-- Default configuration for running with: mvn clean javafx:run -->
                        <id>default-cli</id>
                        <configuration>
                            <mainClass>com.example.demo/com.example.demo.HelloApplication</mainClass>
                            <launcher>app</launcher>
                            <jlinkZipName>app</jlinkZipName>
                            <jlinkImageName>app</jlinkImageName>
                            <noManPages>true</noManPages>
                            <stripDebug>true</stripDebug>
                            <noHeaderFiles>true</noHeaderFiles>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

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);
	}

	@Override
	public 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<Product> 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<Product> queryProducts() {
		List<Product> 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<Product> createTable() {
		TableView<Product> tableView = new TableView<>();
		var col = new TableColumn<Product, String>("名称");
		col.setCellValueFactory(new PropertyValueFactory<Product,String>("productName"));
		tableView.getColumns().add(col);

		var col1 = new TableColumn<Product, Integer>("数量");
		col1.setCellValueFactory(new PropertyValueFactory<Product,Integer>("amount"));
		tableView.getColumns().add(col1);
		var col2 = new TableColumn<Product, Double>("单价");
		col2.setCellValueFactory(new PropertyValueFactory<>("price"));
		tableView.getColumns().add(col2);
		var col3 = new TableColumn<Product, String>("单位");
		col3.setCellValueFactory(new PropertyValueFactory<>("unitName"));
		tableView.getColumns().add(col3);
		return tableView;
	}
}

修改pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>java-demo</groupId>
		<artifactId>root</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>jdbc</artifactId>
	<dependencies>
		<dependency>
			<groupId>org.openjfx</groupId>
			<artifactId>javafx-base</artifactId>
			<version>19</version>
		</dependency>

		<dependency>
			<groupId>org.openjfx</groupId>
			<artifactId>javafx-controls</artifactId>
			<version>19</version>
		</dependency>
		<dependency>
			<groupId>org.openjfx</groupId>
			<artifactId>javafx-graphics</artifactId>
			<version>19</version>
		</dependency>
		<dependency>
			<groupId>org.openjfx</groupId>
			<artifactId>javafx-fxml</artifactId>
			<version>19</version>
		</dependency>
		<dependency>
			<groupId>org.openjfx</groupId>
			<artifactId>javafx-media</artifactId>
			<version>19</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.openjfx</groupId>
				<artifactId>javafx-maven-plugin</artifactId>
				<version>0.0.8</version>
				<configuration>
					<mainClass>org.example.Main</mainClass>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

运行结果:

 建立数据库访问

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

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.5.1</version>
</dependency>

修改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();

最终效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值