文章目录
1.建表语句:
CREATE TABLE public.h_user (
id serial4 not null,
username varchar(50) NULL,
"password" varchar(64) NULL,
nickname varchar(60) NULL,
email varchar(255) NULL,
gender bit(1) NULL,
height float4 NULL,
CONSTRAINT user_pkey PRIMARY KEY (id)
);
2.使用以下方式的预处理方式都报错了
求指教怎么使用预处理PreparedStatement 设置bit(1)的值插入到库中。
package com.health.util;
import java.sql.*;
public class bitTest {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:postgresql://localhost:5432/postgres";
//加 tinyInt1isBit=false 参数也是报错
// String url = "jdbc:postgresql://localhost:5432/postgres?tinyInt1isBit=false";
String username = "postgres";
String password = "postgres";
// SQL语句
String sql = "insert into h_user (username, password, gender,height) values(?,?,?,?)";
try {
// 加载并注册JDBC驱动
Class.forName("org.postgresql.Driver");
// 建立数据库连接
try (Connection conn = DriverManager.getConnection(url, username, password);
// 创建PreparedStatement
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, "ztt");
pstmt.setString(2, "123456");
// 设置bit(1)值,这里下面设置的情况都报错
// pstmt.setObject(3, new Boolean(true));
// pstmt.setObject(3, true,Types.BIT);
// pstmt.setObject(3,new Byte("1"));
// pstmt.setObject(3, new Short("1"),Types.BIT);
// pstmt.setObject(3,1);
pstmt.setObject(3,1,Types.BIT);
pstmt.setFloat(4, 170);
// 执行SQL语句
pstmt.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.可以先用sql拼接实现功能
package com.health.util;
import java.sql.*;
public class bitTest {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:postgresql://localhost:5432/postgres";
String username = "postgres";
String password = "postgres";
// SQL语句 也可以把0::bit替换成cast(1 as bit(1))也可设置成功
String sql = "insert into h_user (username, password, gender,height) values('ztt1','123',0::bit,172)";
try {
// 加载并注册JDBC驱动
Class.forName("org.postgresql.Driver");
try (Connection conn = DriverManager.getConnection(url, username, password);
// 创建Statement
Statement stat = conn.createStatement()) {
// 执行SQL语句
int result = stat.executeUpdate(sql);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
标签:jdbc,Postgresql,String,postgres,sql,bit,password,pstmt
From: https://blog.csdn.net/weixin_44231698/article/details/140682745