gpt4 book ai didi

java - 如何使用 PrepareStatement 在 Java 中执行 INSERT SELECT INTO

转载 作者:行者123 更新时间:2023-11-30 08:42:51 25 4
gpt4 key购买 nike

我正在尝试执行 INSERT INTO SELECT,它通过从 2 个表的列中选择特定数据插入到 1 个表中。问题是,它也将涉及来自 JTextField 的用户输入。我已经搜索了很多解决方案,但仍然出现错误,我只是不知道还能做什么。我使用 Java 作为 PL,使用 Oracle 作为 DB。这是我到目前为止所得到的:

Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","ghost","slayer");

stmt = con.createStatement();

String sbjC = sbjCode.getText(); //textfield for subjectCode
String sbjN = sbjName.getText(); //textfield for subjectName
String matricsno = textstudentid.getText(); //textfield for matrics number
String sbjG = sbjGrade.getText(); //textfield for subjectGrade (not gonna be use in db, just for comparison)

String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = '"+sbjC+"' AND b.subjectName = '"+sbjN+"' AND s.matricsNo = '"+matricsno+"'";

/* table Transferred has 5 column which are subjectCode,subjectName,credit,prequisite,matricsNo [matricsno as FK]
* table bitm has 5 column [subjectCode as PK]
* table student has 6 column [matricsno as PK]
*/

ps = con.prepareStatement(sql1);

ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, "SELECT credit FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(4, "SELECT prequisite FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(5, "SELECT matricsno FROM student WHERE matricsno = '"+matricsno+"'");

ps.executeUpdate(sql1);

在执行并将所有需要的数据插入 JTextField 后,我遇到的唯一错误是 java.sql.SQLException : Invalid column index

SQL语句已在SQL Developer中测试成功。只是我对如何在 Java 上做到这一点感到困惑。感谢您的所有回复和时间。我是 Java 新手。

最佳答案

对于 PreparedStatement,您要编写代码?进入 sql,然后用值替换它。

String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ? ";


ps = con.prepareStatement(sql1);

ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3,matricsno);

ps.executeUpdate ();

应该这样做。

您的错误来自于没有匹配的参数 (setString...)?

关于java - 如何使用 PrepareStatement 在 Java 中执行 INSERT SELECT INTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34441419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com