使用 PreparedStatement 插入记录的 Java 程序

PreparedStatement 用于预编译可能包含输入参数的 SQL 语句。在这篇文章中,我们将开发一个 Java 或 JDBC 程序来使用 PreparedStatement 将记录插入到表中。PreparedStatement 是 JDBC 驱动程序软件提供的 Java 类的对象,该类实现 java.sql.PreparedStatement(I)。java.sql.PreparedStatement(I) 是从 java.sql.Statement(I) 扩展而来的。

在这里,我们将使用Oracle 数据库,但您可以使用任何具有所需信息的数据库。

要插入记录,我们需要一个表,我们也可以使用现有的表。在这里,我们正在创建一个表“产品”,其中将包含产品编号 (pid)、产品名称、产品价格和产品数量的详细信息。

在Oracle数据库中创建表,

create table product
(
     pid number(10) primary key, 
     pname varchar2(15), 
     price float,
     quantity number(10)
);

如何编写代码

1. 使用位置参数/占位符/位置解析器(?)准备 SQL 查询

String query = "INSERT INTO PRODUCT VALUES(?,?,?,?)";

这里?的符号代表以后可以设置值的参数。第一个?代表第一列即product_number,第二个?代表产品名称,第?三个代表价格,第四个?代表数量。

SQL 查询将在整个应用程序中保持不变,因此,我们通常将 SQL 查询作为类顶部的字符串常量。其他原因是:-
a) 轻松识别它们并轻松修改它们。
b)在代码的其他部分看到它们不可修改,
c)在没有对象的代码的其他部分中访问它们。

静态最终变量称为常量。通常,这些变量名称将采用大写字母,以便与其他变量区分开来。

  1. 向数据库软件发送 SQL 查询。
    在数据库软件中将该 SQL 查询作为预编译的 SQL 查询,并获取表示 SQL 查询的 PreparedStatement 对象。
PreparedStatement ps = con.prepareStatement(query);

预编译的 SQL 查询已准备就绪,现在它只会进入数据库执行。

3. 使用 setXxx(-) 方法将输入值设置为预编译的 SQL 查询参数(?)。

ps.setInt(1,1001); // product id

// product name
ps.setString(2, “Fan”); 

// price of product
ps.setString(3, “500”); 

ps.setFloat(4, 2); // quantity

4.在数据库软件中执行预编译的SQL查询,

int result = ps.executeUpdate();

5.处理结果,

if(result == 0) 
System.out.println("Not inserted");
else
System.out.println("record inserted");

6. 以相同或不同的值多次执行上述预编译的 SQL 查询(重复 3 到 5 步)

7. 关闭 JDBC 对象。

ps.close();
con.close();

Java / JDBC程序使用preparedstatement插入记录

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class InertRecord {

   // SQL query
   private static final String INSERT_PRODUCT_QUERY = 
               "INSERT INTO PRODUCT VALUES(?,?,?,?)";

   public static void main(String[] args ) {

      // declare variables
      Scanner scan = null;
      int item=0, pid = 0, qty = 0;
      String name = null;
      float price = 0.0f;
      Connection con = null;
      PreparedStatement ps = null;
      int result = 0;

      try {
         // read input 
         scan = new Scanner(System.in);
         if(scan != null) {
            System.out.print("Enter the number of items: ");
            item = scan.nextInt();
         }

         // establish the connection
         con = DriverManager.getConnection(
            "jdbc:oracle:thin:@localhost:1521:knowprogram",
            "scott", "tiger");

         // compile SQL query and 
         // store it in PreparedStatemet object
         if(con != null)
            ps = con.prepareStatement(INSERT_PRODUCT_QUERY);

         // read multiple set of inputs from end-user
         // set input values and execute the query
         if(scan != null && ps != null) {
            for(int i=0; i < item; i++) {

               // read inputs
               System.out.println("\nEnter item-"+ (i+1) +
                               " details, ");
               System.out.print("Product ID: ");
               pid = scan.nextInt();
               System.out.print("Name: ");
               name = scan.next();
               System.out.print("Price: ");
               price = scan.nextFloat();
               System.out.print("Quantity: ");
               qty = scan.nextInt();

               // set input values to query parameters
               ps.setInt(1, pid);
               ps.setString(2, name);
               ps.setFloat(3, price);
               ps.setInt(4, qty);

               // execute the query
               result = ps.executeUpdate();
           }
        }

        // process the result
        if(result == 0)
            System.out.println("\nRecords not inserted");
        else
            System.out.println("\nRecords inserted"+
                                     " successfully");

     } catch(SQLException se) {
        se.printStackTrace();
     } catch(Exception e) {
        e.printStackTrace();
     } // end of try-catch block
 
     finally {
        // close JDBC objects
        try {
           if(ps != null) ps.close();
        } catch(SQLException se) {
           se.printStackTrace();
        }
        try {
           if(con != null) con.close();
        } catch(SQLException se) {
           se.printStackTrace();
        }
        try {
           if(scan != null) scan.close();
        } catch(Exception e) {
           e.printStackTrace();
        }
     }

   } //end of main
} //end of class

输出:-

Enter the number of items: 3

Enter item-1 details,
Product ID: 102
Name: Chair
Price: 500
Quantity: 5

Enter item-2 details,
Product ID: 2051
Name: Fan
Price: 999
Quantity: 2

Enter item-3 details,
Product ID: 111
Name: Table
Price: 1500
Quantity: 1

Records inserted successfully.

现在,验证记录是否插入到 Oracle 数据库中?

SQL> select * from product;

PID  PNAME   PRICE  QUANTITY
---- ------- ----- ----------
 102  Chair   500      5
2051  Fan     999      2
 111  Table   1500     1

我们已经成功地在表中插入了记录。在接下来的 JDBC 程序示例中,我们将更新,并显示表的记录。

如果您想知道引发异常的具体原因,我们可以通过调用打印基于 SQL 错误代码的消息。请注意,产品 id 是主键,因此不能重复,如果我们尝试插入与现有产品 id 相同的记录,那么 Oracle 服务器会返回错误:ORA-00001:违反唯一约束 (SCOTT.SYS_C0012404) . 同样,当我们尝试为产品 ID 插入太大的值时,我们会收到错误:ORA-12899getErrorCode()

try {
   // JDBC code
} catch(SQLException se) {

   if(se.getErrorCode()==1)
      System.out.println("Product Id already exist");

   else if(se.getErrorCode()==12899)
      System.out.println("Value is too large for the column");

   else
      System.out.println("Unknown problem from database");

   se.printStackTrace();
} catch(Exception e) {
   e.printStackTrace();
} // end of try-catch block

当 JDBC 应用程序向数据库软件发送非选择查询时,该查询在自动提交环境中的数据库软件中执行。这意味着查询执行结果将立即提交,以便我们以后无法回滚。在处理非选择查询时,不需要 ResultSet 对象。JDBC 中的所有操作都通过 JDBC 驱动程序在数据库软件上进行。

如果您喜欢这篇文章,请与您的朋友分享。您想分享有关上述主题的更多信息,还是您发现任何不正确的地方?让我们在评论中知道。谢谢!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值