插入操作
说明: 插入操作执行前需要确保执行了创建表操作,表名为test,表结构如下。
create table test (id int,name varchar (10));
-
使用Statement执行插入操作,后面可以跟随查询语句检查插入是否生效。
public static void main(String[] args) throws SQLException { Connection conn = getConnect(); Statement statement = conn.createStatement(); statement.execute("insert into test (id,name) values (2,'zhangsan')"); PreparedStatement preparedStatement=conn.prepareStatement("select * from test;"); ResultSet resultSet=preparedStatement.executeQuery(); while (resultSet.next()){ System.out.println(resultSet.getObject("id")+" "+ resultSet.getObject("name")); } conn.close(); } public static Connection getConnect() { String driver = "org.opengauss.Driver"; String sourceURL = "jdbc:opengauss://127.0.0.1:8080/test?user=myuser&password=myPassWord"; Properties info = new Properties(); Connection conn = null; try { Class.forName(driver); } catch (Exception var9) { var9.printStackTrace(); return null; } try { conn = DriverManager.getConnection(sourceURL); System.out.println("连接成功!"); return conn; } catch (Exception var8) { var8.printStackTrace(); return null; } }
-
使用PreparedStatement 执行插入操作,后面可以跟随查询语句检查插入是否生效。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JdbcConn { public static void main(String[] args) throws SQLException { Connection conn = getConnect(); Statement statement = conn.createStatement(); PreparedStatement preparedStatement=conn.prepareStatement("insert into test (id,name) values (3,'zhaoliu')"); preparedStatement.execute(); preparedStatement=conn.prepareStatement("select * from test;"); ResultSet resultSet=preparedStatement.executeQuery(); while (resultSet.next()){ System.out.println(resultSet.getObject("id")+" "+ resultSet.getObject("name")); } conn.close(); } public static Connection getConnect() { String driver = "org.opengauss.Driver"; String sourceURL = "jdbc:opengauss://127.0.0.1:8080/test?user=myuser&password=myPassWord"; Properties info = new Properties(); Connection conn = null; try { Class.forName(driver); } catch (Exception var9) { var9.printStackTrace(); return null; } try { conn = DriverManager.getConnection(sourceURL); System.out.println("连接成功!"); return conn; } catch (Exception var8) { var8.printStackTrace(); return null; } } }