import java.sql.*;
import javax.swing.*;
import java.awt.event.*;/**
*
* @author FC
*/
public class Applicant extends JFrame{
JPanel panel=new JPanel();
JLabel label1=new JLabel("ID");
JLabel label2=new JLabel("Name");
JLabel label3=new JLabel("Address");
JLabel label4=new JLabel("Position");
private JTextField textID=new JTextField(8);
private JTextField textName=new JTextField(8);
private JTextField textAddress=new JTextField(30);
String position[]={"市场部经理","市场咨询人员","会计"};
JComboBox box=new JComboBox(position);
private JButton buttonSubmit=new JButton("提交");
private JButton buttonReset=new JButton("重置");
String driver="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:con_java";
String user="sa";
String password="hanjian";
String recid=this.textID.getText();
String recname=this.textName.getText();
String recaddress=this.textAddress.getText();
String recposition=(String)box.getSelectedItem();
/** Creates a new instance of Applicant */
public Applicant() {
this.getContentPane().add(panel);
panel.add(label1);
panel.add(textID);
panel.add(label2);
panel.add(textName);
panel.add(label3);
panel.add(textAddress);
panel.add(label4);
panel.add(box);
panel.add(buttonReset);
panel.add(buttonSubmit);
ActionListener a=new MyAction();
buttonSubmit.addActionListener(a);
buttonReset.addActionListener(new MyAction());
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(3);
}
class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
Object obj=e.getSource();
if(obj==buttonSubmit){
if(textID.getText().length()==0){
JOptionPane.showMessageDialog(null,"ID不能为空");
}
else if (textName.getText().length()==0){
JOptionPane.showMessageDialog(null ,"姓名不能为空");
}
else if (textAddress.getText().length()==0){
JOptionPane.showMessageDialog(null,"地址不能为空");
}
try{
Class.forName(driver);
Connection conn=DriverManager.getConnection(url,user,password);
String sql="insert into Applicant values(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String recid=textID.getText();
String recname=textName.getText();
String recaddress=textAddress.getText();
String recposition=(String)box.getSelectedItem();
ps.setString(1, recid);
ps.setString(2, recname);
ps.setString(3, recaddress);
ps.setString(4,recposition);
为什么这段注释代码必须放在ps.setString()之前呢,若放在setString()后面就没法往数据库中添加数据了,请问这是怎么回事?多谢
/* String recid=textID.getText();
String recname=textName.getText();
String recaddress=textAddress.getText();
String recposition=(String)box.getSelectedItem();*/
ps.executeUpdate();
JOptionPane.showMessageDialog(null ,"信息添加成功");
}
catch(Exception a){
System.out.println("error"+a);
}
}
if(obj==buttonReset){
textID.setText("");
textAddress.setText("");
textName.setText("");
}
}
}
public static void main(String args[]){
new Applicant();
}
}
同意