[英]How to use PreparedStatement with JDBC
我是 JDBC 和 Java 的新手。
我来自 Javascript 和 Typescript 背景。 我决定通过创建一个小型基础项目来学习 JDBC 和 Oracle。
我正在使用JDK 8
。 我正在关注这个学习材料: TutorialsPoint-PreparedStatement 。 我发现问题出在我的DataService 上。
这是我的DataService
类:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataService {
Connection con;
PreparedStatement pstmt;
static String branch_name="";
static LocalDate branch_created_on;
static String branch_pulled_from="";
DataService() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","scott");
}
catch(Exception e){
System.out.println(e);
}
}
public void getValue() {
branch_name=AddNewBranchRecord.branchNameTextField.getText();
branch_created_on=AddNewBranchRecord.datePicker1.getValue();
branch_pulled_from=(String) AddNewBranchRecord.combo_box_1.getValue();
}
public void putValue() {
System.out.println("Branch name: "+branch_name);
System.out.println("Branch created on: "+branch_created_on);
System.out.println("Branch pulled from: "+branch_pulled_from);
}
public void insertRecord() {
System.out.println("Adding a record...");
getValue();
try {
String sql;
sql = "insert into mybranches values (branch_name, branch_created_on, branch_pulled_from);";
pstmt = con.prepareStatement(sql);
} catch (SQLException ex) {
Logger.getLogger(DataService.class.getName()).log(Level.SEVERE, null, ex);
}
pstmt .close();
}
}
我确定我错过了一些东西。
我没有收到任何错误或异常,但没有在数据库中插入任何行。
我与select * from mybranches
交叉检查。
但是,如果我使用普通的Statement
,则相同的代码可以完美运行。
您创建了PreparedStatement
但不使用它。
准备好的语句用于例如将不同的值多次插入表中。
像执行普通语句一样创建PreparedStatement
一次并包含?
而不是不同的值。
如果你想执行它,你必须使用setXXX(int,Type)
方法设置值( ?
s 将被它们替换setXXX(int,Type)
,然后使用.execute()
执行它。
正如问题的评论中所指出的,SQL 代码无效。 sql代码准备好的语句就像普通语句的sql代码一样,但是一直在变化的值被替换为?
.
准备好的语句的 SQL 代码类似于:
INSERT INTO mybranches VALUES (?,?,?)
如果要使用PreparedStatement
,可以设置如下值:
pstmt.setString(1,branch_name);
pstmt.setObject(2,branch_created_from);
pstmt.setString(3,branch_pulled_from);
最后,执行它
pstmt.execute();
请注意(正如我已经说过的)您应该创建PreparedStatement
一次,而不是每次执行insertRecord()
方法时,在该方法中,您应该只调用setXXX
方法和execute()
方法。
当您不再需要PreparedStatement
(和Connection
对象)时,应将其关闭。
另外,作为@TT。 在评论中建议,您应该在INSERT
语句中指定列。 它会是这样的
INSERT INTO mybranches (name,createdFrom,pulledFrom) VALUES (?,?,?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.