在数据库中插入一行的JDBC语句示例。
RowInsert.java
package com.mkyong.jdbc.statement.row;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
public class RowInsert {
public static void main(String[] args) {
// auto close connection and statement
try (Connection conn = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
Statement statement = conn.createStatement()) {
int row = statement.executeUpdate(generateInsert("mkyong", new BigDecimal(999.80)));
// rows affected
System.out.println(row);
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
private static String generateInsert(String name, BigDecimal salary) {
return "INSERT INTO EMPLOYEE (NAME, SALARY, CREATED_DATE) " +
"VALUES ('" + name + "','" + salary + "','" + LocalDateTime.now() + "')";
}
}
表定义。
CREATE TABLE EMPLOYEE
(
ID serial,
NAME varchar(100) NOT NULL,
SALARY numeric(15, 2) NOT NULL,
CREATED_DATE timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP
PRIMARY KEY (ID)
);
PS已通过PostgreSQL 11和Java 8测试
pom.xml
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
下载源代码
$ git clone https://github.com/mkyong/java-jdbc.git
参考文献
翻译自: https://mkyong.com/jdbc/jdbc-statement-example-insert-a-record/