扩展协议插入数据
最近更新时间: 2024-10-17 17:10:00
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import java.util.Random;
public class insert_prepared_return {
public static void main(String args[]) {
Connection c = null;
PreparedStatement stmt;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://172.16.0.23:11345/postgres","adichen", "tbase");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
//插入数据
String sql = "INSERT INTO public.t1 (f1,f2) VALUES (?,?) returning *";
stmt = c.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, 1);
stmt.setString(2, "111");
stmt.executeUpdate();
ResultSet generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) {
long f1 = generatedKeys.getLong(1);
String f2 = generatedKeys.getString(2);
System.out.println(f1);
System.out.println(f2);
}
generatedKeys.close();
stmt.close();
//c.commit();
c.close();
} catch (Exception e) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
}
}