这是我在oracle中的表:
CREATE TABLE "STUDENT"
( "STU_ID" NUMBER(10,0),
"NAME" VARCHAR2(20),
"MOBILENO" NUMBER(10,0),
"EMAIL" VARCHAR2(50),
"ADDRESS" VARCHAR2(100),
"STREAM" CHAR(50),
"SEMESTER" CHAR(50),
"DATE_OF_BIRTH" DATE,
CONSTRAINT "PK_STU_ID" PRIMARY KEY ("STU_ID") ENABLE
) ;
我想通过在eclipse中按下添加按钮将学生信息存储在上表中。当尝试执行此行“st.executeUpdate(sql);”时,这是代码:
JLabel lblAdd = new JLabel(" Add");
lblAdd.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
Clock=new Timer(5000,null);
Clock.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
try {
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/XE","ADMIN","admin");
Statement st=con.createStatement();
ResultSet rslt=st.executeQuery("select * from student");
ResultSet stu_seq=st.executeQuery("select student_sequence.nextval from DUAL");
System.out.println("getting resultset");
if(stu_seq.next())
{ System.out.println(stu_seq.getInt(1));
String name=txtNm.getText().trim();
String email=txtEmailid.getText().trim();
String mobile=txtMobileNo.getText().trim();
String sql="INSERT INTO student(STU_ID,NAME,MOBILENO,EMAIL,ADDRESS,DATE_OF_BIRTH,STREAM,SEMESTER) VALUES ("+stu_seq.getInt(1)+",'"+name+"','"+mobile+"','"+email+"',";
sql+="'"+txtPrmntAdd.getText().trim()+"',";
sql+="'"+cmbDay.getSelectedItem()+"'";
sql+="'"+cmbMnth.getSelectedItem()+"'";
sql+="'"+cmbYr.getSelectedItem()+"',";
sql+="'"+cmbRgstrStrm.getSelectedItem()+"',";
sql+="'"+cmbRgstrSem.getSelectedItem()+"',";
sql+=")";
st.executeUpdate(sql);
// System.out.println("after executing");
}
System.out.println("Inserted into database");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frameReset();
//lblStatus.setText("data saved successfully");
//lblAni.setVisible(false);
Clock.stop();
}
});
Clock.start();
//lblStatus.setVisible(true);
//lblAni.setVisible(true);
}
});
lblAdd.setBounds(172, 340, 60, 18);
panelRegister.add(lblAdd);
lblAdd.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblAdd.setForeground(new Color(0, 51, 102));
lblAdd.setFont(new Font("Tw Cen MT", Font.PLAIN, 16));
lblAdd.setIcon(new ImageIcon(Student.class.getResource("/img/Add-New-16.png")));
想要将学生信息存储在table.where我做错了所以我错过了表达式错误?
答案 0 :(得分:3)
您的代码片段错误:
sql+="'"+cmbRgstrSem.getSelectedItem()+"',";
sql+=")";
因为它在INSERT语句的末尾给出了以下结果:
INSERT ....VALUES( ...... , 'someValue',)
数据库需要在最后一个逗号后面的下一个值,但没有任何内容。
顺便说一句,使用PreparedStatement来完成这样的任务,
有关详细信息,请参阅此链接 - 这是Oracle的教程:"使用准备好的语句" :https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
研究这个答案,知道为什么要使用PreparedStatement:
When should we use a PreparedStatement instead of a Statement?