当前位置:网站首页>使用 Preparedstatement 选择和显示记录的 JDBC 程序
使用 Preparedstatement 选择和显示记录的 JDBC 程序
2022-07-23 14:29:00 【allway2】
在之前的 JDBC 教程中,我们了解了PreparedStatement对象,后来我们开发了一个Java 程序来向表中插入记录,以及另一个程序来更新表的记录。现在,在这篇文章中,我们将发布一个 Java 程序来使用 PreparedStatement 对象选择和显示记录。
要获取表的记录,我们需要 ResultSet 对象并使用 ResultSet 的 getXxx(-) 方法,我们可以获取表的详细信息。
我们正在使用 Oracle 数据库,但您可以使用任何具有所需信息的数据库。在 Oracle 数据库中,我们有一个产品表,其中包含产品 ID、产品名称、产品价格和数量的详细信息。
SQL> SELECT * FROM product;
PID PNAME PRICE QUANTITY
----- -------- ------- ----------
102 Bed 2000 1
2051 Fan 999 2
111 Table 1500 1SQL> DESC product;
Name Null? Type
--------- -------- ----------
PID NOT NULL NUMBER(10)
PNAME VARCHAR2(15)
PRICE FLOAT(126)
QUANTITY NUMBER(10)我们要显示产品表的记录。因此,不需要从最终用户那里获取任何输入值,也不需要设置查询参数。
所需的 SQL 查询是,
SQL> SELECT pid, pname, price,
quantity FROM product;注意:- 在开发 JDBC 应用程序时,不建议在 SQL 查询中使用 *,因此不建议使用。SELECT * FROM product
显示表格记录的Java程序
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DisplayProductTable {
// SQL query
private static final String SELECT_PRODUCT_QUERY =
"SELECT PID, PNAME, PRICE, QUANTITY FROM PRODUCT";
public static void main(String[] args ) {
// declare variables
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 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(SELECT_PRODUCT_QUERY);
// execute the query
if(ps != null) {
rs = ps.executeQuery();
}
// process the result
if(rs != null) {
while(rs.next()) {
System.out.println(""
+ rs.getInt("PID") +" "
+ rs.getString("PNAME") +" "
+ rs.getFloat("PRICE") +" "
+ rs.getInt("QUANTITY"));
}
}
System.out.println("\nRecords displayed");
} 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();
}
}
} //end of main
} //end of class输出:-
102 Bed 2000.0 1
2051 Fan 999.0 2
111 Table 1500.0 1
Records displayed使用 PreparedStatement 根据给定值选择和显示记录
现在让我们开发另一个 JDBC 程序,它将根据给定的值选择行并仅显示那些行的详细信息。
必需的 SQL 查询,
SQL> SELECT pname, price, quantity
FROM product WHERE pid = 102;
PNAME PRICE QUANTITY
------- ---------- ----------
Bed 2000 1import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class SelectTest {
// SQL query
private static final String SELECT_PRODUCT_QUERY =
"SELECT PNAME, PRICE, QUANTITY FROM PRODUCT"+
" WHERE PID = ?";
public static void main(String[] args ) {
// declare variables
Scanner scan = null;
int pid = 0;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean flag = false;
try {
// read input
scan = new Scanner(System.in);
if(scan != null) {
System.out.print("Enter product ID: ");
pid = 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(SELECT_PRODUCT_QUERY);
// set input value to query parameter
if(ps != null)
ps.setInt(1, pid);
// execute the query
if(ps != null)
rs = ps.executeQuery();
// process the result
if(rs != null) {
while(rs.next()) {
flag = true;
System.out.println(""
+ rs.getString("PNAME") +" "
+ rs.getFloat("PRICE") +" "
+ rs.getInt("QUANTITY"));
}
}
if(flag)
System.out.println("Records fetched & displayed");
else
System.out.println("Records not found");
} 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 product ID: 102
Bed 2000.0 1
Records fetched & displayed
Enter product ID: 1000
Records not found
如果您喜欢这篇文章,请与您的朋友分享。您想分享有关上述主题的更多信息,还是您发现任何不正确的地方?让我们在评论中知道。谢谢!
边栏推荐
猜你喜欢

Wechat applet wx.hideloading() will close the toast prompt box

IR Drop 、EM、Noise 和Antenna

When does MySQL use table locks and row locks?

软件质量体系之思

Dead beat recursion 1: recursive formula

VMware虚拟机的三种网络模式

场景小小记

Explain SQL optimization in detail

Lake Shore - empx-h2 low temperature probe station

【mysql集群故障恢复】
随机推荐
Solve data functions should return an object (property "visible" must be accessed with "$data.visible")
Pymoo学习 (4): 多标准决策
CSR、SSR 与 SSG
Pymoo学习 (3):使用多目标优化找到最优解的集合
腾讯撕开中国NFT的“遮羞布”
docker 安装redis
Pyinstaller+installforge multi file project software packaging
Pymoo学习 (2):带约束的双目标优化问题
Function secondary development / plug-in development of JMeter (detailed version)
SQL bool盲注和时间盲注详解
PIP reports an error could not find a version that satisfies the... No matching distribution
小程序商城如何精细化运营?
图的先深搜索、图的先广搜索 (三种方法实现)
Compose canvas pie chart effect drawing
Fundamentals of C language -- 2-6 pointers, arrays and sizeof operators
IR Drop 、EM、Noise 和Antenna
Fundamentals of C language -- the data type meaning of 2-4 pointers and the analysis of forced type conversion
[untitled]
Weisfeiler Lehman graph isomorphism test and others
Vscode - code and file changes cannot be saved