gpt4 book ai didi

java - 如何使用 JDBC 在数据库中插入引用值?

转载 作者:行者123 更新时间:2023-11-29 08:12:44 30 4
gpt4 key购买 nike

我正在尝试使用下面的代码将值插入 Oracle 10g 数据库,但它在执行时给出了“Missing Expression”错误。我必须将引用值传递到插入子句中,但不知道确切的语法或方法。请帮我解决这个问题。谢谢。

学生表:-

                      Sid       VARCHAR2(200) PRIMARY KEY  CHECK(Sid>0),
Pass_word VARCHAR2(10) NOT NULL,
S_name VARCHAR2(20) NOT NULL,
G_name VARCHAR2(20) ,
Branch VARCHAR2(10) NOT NULL,
D_company VARCHAR2(20) ,
B_Percent INT NOT NULL CHECK(B_Percent<100),
twelth_percent INT NOT NULL CHECK(twelth_percent<100),
tenth_percent INT NOT NULL CHECK(tenth_percent<100),
Certify VARCHAR2(30),
Semester INT NOT NULL CHECK(Semester<9),
D_Birth DATE NOT NULL,
Sex VARCHAR2(6) NOT NULL

代码:

Connection connection = null;

try
{

// Load the JDBC driver

String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";

Class.forName(driverName);

connection = DriverManager.getConnection("jdbc:odbc:placement","siddharth","sid");

studentID = StudentID.getText();
spassword = PasswordField.getPassword();
studentname = NameField.getText();
Gname = GuardianField.getText();
branch = BranchField.getText();
dcompany = DcompanyField.getText();
bpercent = BtechField1.getText();
twelthpercent = TwelthField.getText();
tenthpercent = TenthField.getText();
semester = SemesterField.getText();
certify = CertificationField.getText();
sex = SexCombo.getActionCommand();
date = (Date) DateTextField1.getValue();



Statement stmt = connection.createStatement();
stmt.executeUpdate("insert into student " +"(sid,pass_word,s_name,g_name,branch,d_company,b_percent,twelth_percent,tenth_percent,certify,semester,d_birth,sex)"+
"values(studentID, spassword,studentname,Gname,branch,dcompany,bpercent,twelthpercent,tenthpercent,certify,semester,date,sex)" );

stmt.close();
connection.close();
}

catch (ClassNotFoundException e) {
// Could not find the database driver
JOptionPane.showMessageDialog(null,e);
}
catch (SQLException e) {
// Could not connect to the database
JOptionPane.showMessageDialog(null,e);
}

最佳答案

当前您的 SQL 语句如下所示:

insert into student (sid, pass_word, ...) values (studentID, spassword, ...)

变量名对 SQL 本身没有任何意义。

您应该使用准备好的语句。例如,您的 SQL 应如下所示:

insert into student (sid, pass_word, ...) values (?, ?, ...)

然后你使用:

PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, studentID);
stmt.setString(2, spassword);

// etc

参见 JDBC tutorial on prepared statements获取更多信息。

关于java - 如何使用 JDBC 在数据库中插入引用值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7140345/

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