使用netbeans从MYSql中检索数据,使用PreparedStatement和ResultSet

时间:2016-03-22 16:35:54

标签: java mysql swing netbeans javacv

这是一个很大的代码,但请帮助我!我正在做一个关于人脸识别(OpenCV Libraries)的项目,用它来标记项目认可的学生的出勤率!我的项目已准备就绪但只能从我的JFrame中使用的JTextField中检索文本...我正在使用MYSql和Netbeans!

这是代码!

import static cern.jet.math.Bessel.i1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import facedetection.*;
import com.googlecode.javacv.*;
import com.googlecode.javacv.cpp.*;
import com.googlecode.javacpp.Loader;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class FaceRecognizer extends JFrame 
{
  // GUI components
  private FaceRecogPanel facePanel;
  private JButton recogBut;
  private JTextField nameField;     // where the name (and distance info) appears
  private JButton done;
  private JButton exit;


  public FaceRecognizer()
  {
    super("Face Recognizer");
    FaceRecognizer fac;
    Container c = getContentPane();
    c.setLayout( new BorderLayout() );   

    // Preload the opencv_objdetect module to work around a known bug.
    Loader.load(opencv_objdetect.class);

    facePanel = new FaceRecogPanel(this); // the sequence of pictures appear here
    c.add( facePanel, BorderLayout.CENTER);


    // button for recognizing a highlighted face
    done = new JButton("Done");
    recogBut = new JButton("Recognize Face");
    recogBut.addActionListener( new ActionListener() {
       public void actionPerformed(ActionEvent e)
       { nameField.setText("");
         recogBut.setEnabled(false);
         facePanel.setRecog();
       }
    });
    done.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
      {
          WelcomeStaffs wc = new WelcomeStaffs();
          Connection con = null;
          try{
            String url = "jdbc:mysql://localhost:3306/facedetection";
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Conncection Success");
            con = (Connection) DriverManager.getConnection(url, "root", "2204");
            System.out.println("Database Connected");
            System.out.println(nameField.getText());
             }
          catch(Exception ex)
          {
              System.out.println("Exception = "+ex);
          }
          String nm = nameField.getText().toUpperCase();
          String name ="",course="";
          String subject = wc.subject_txt.getText();
          String staff = wc.staff_txt.getText();
          String day = wc.day_txt.getText();
         // String tempd = wc.date_txt.getText().trim();
         // String tempt = wc.time_txt.getText().trim();
          int roll_no = 0;
         // int date = Integer.parseInt(tempd);
        //  int time = Integer.parseInt(tempt);
          String sql = "select roll_no,name,course from students where name= ? ";
          try {

              PreparedStatement ps = con.prepareStatement(sql);
              ps.setString(1,nm);

              ResultSet rs = ps.executeQuery(sql);
              while(rs.next()) //retrieving values from database and storing it!
              {
                  roll_no = rs.getInt("roll_no");
                  name = rs.getString("name");
                  course = rs.getString("course");
                  System.out.println("Retrieved Data!!!!!!!"+name+course);
              }
          } catch (SQLException ex) {
              Logger.getLogger(FaceRecognizer.class.getName()).log(Level.SEVERE, null, ex);
          }
          try{
              if(roll_no == 0 && name.equals("") && course.equals(""))
              {
                  System.out.println("EMPTY");
              }
              else
              {
                sql = "INSERT INTO attendance(roll_no, name, course, subject, staff, day) VALUES(?,?,?,?,?,?)";
              PreparedStatement ps1 = con.prepareStatement(sql);
              ps1.setInt(1,roll_no);
              ps1.setString(2,name);
              ps1.setString(3,course);
              ps1.setString(4,subject);
              ps1.setString(5,staff);
              ps1.setString(6,day);
           //   ps1.setInt(7,date);
            //  ps1.setInt(8,time);
              int i1 = ps1.executeUpdate();
              System.out.println("Data Inserted"+i1);
              }

          }
          catch(Exception ec)
          {
              System.out.println(""+ec);
          }

      }
  });

    nameField = new JTextField(20);   // for the name of the recognized face
    nameField.setEditable(false);

    JPanel p = new JPanel();
    p.add(recogBut);
    p.add( new JLabel("Name: "));
    p.add( nameField);
    p.add(done);
    c.add(p, BorderLayout.SOUTH);


    addWindowListener( new WindowAdapter() {
      public void windowClosing(WindowEvent e)
      { facePanel.closeDown();    // stop snapping pics
        /*Attendance_Chart ac = new Attendance_Chart();
        ac.setVisible(true);*/
        System.exit(0);
      }
    });

    pack();  
    setResizable(false);
    setVisible(true);
  } // end of FaceRecognizer()



  public void setRecogName(final String faceName, final String dist)
  // update face name and its distance in the nameField; called from panel
  { 
    SwingUtilities.invokeLater(new Runnable() {
      public void run() 
      {  nameField.setText( faceName);  
         recogBut.setEnabled(true);
      }
    });
  }  // end of setRecogName()


  // -------------------------------------------------------

  public static void main( String args[] )
  {  new FaceRecognizer(); 

  }

} // end of FaceRecognizer class

我得到的例外就是这个!按下完成按钮!

Mar 22, 2016 10:04:49 PM FaceRecognizer$2 actionPerformed
SEVERE: null
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2788)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2738)
    at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1617)
    at FaceRecognizer$2.actionPerformed(FaceRecognizer.java:89)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

1 个答案:

答案 0 :(得分:2)

更改行

 ResultSet rs = ps.executeQuery();

select roll_no,name,course from students where name= ?

(否则你正在执行{{1}}作为静态SQL语句 - 而且Mysql抱怨参数通配符。)

相关问题