如何使用SQL和Netbeans从数据库中删除行?

时间:2022-07-20 02:50:19

I have a problem with netbeans. I would like to remove a row from my database after push a jbutton but I can not.

我有netbeans的问题。我想在按下jbutton后从我的数据库中删除一行,但我不能。

I have like errors:

我有错误:

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 'car_manufacturing,modelyear,carprice' 

Below is my code:

以下是我的代码:

package cargestion;

import javax.swing.table.DefaultTableModel;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 *
 */
public class FenetreListeOutil extends javax.swing.JFrame {

  Statement stmt;
  Statement stmtcarlist;
  Connexion myconnexion = new Connexion();

  /**
   * Creates new form Fenetrecarlist
   */
  public Fenetrecarlist() {

    initComponents();

    DefaultTableModel model = new DefaultTableModel();

    model.addColumn("NAMECAR");
    model.addColumn("CAR MANUFACTURING");
    model.addColumn("Year");
    model.addColumn("PRICE");

    String requetecarlist = "select *from car";
    try {

      stmtcarlist = myconnexion.ObtenirConnexion().createStatement();
      ResultSet resultat = stmtcarlist.executeQuery(requetecarlist);
      while (resultat.next()) {
        model.addRow(new Object[]{resultat.getString("namecar"), resultat.getString("car_manufacturing"), resultat.getString("Modelyear"), resultat.getString("carprice")});
      }
    } catch (SQLException ex) {
      System.out.println(ex);

    }

    Tablecar.setModel(model);
  }

  /**
   * This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    Tablecar = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setName("Form"); // NOI18N

    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cargestion.cargestionApp.class).getContext().getResourceMap(Fenetrecarlist.class);
    jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
    jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
    jLabel1.setName("jLabel1"); // NOI18N

    jScrollPane1.setName("jScrollPane1"); // NOI18N

    TableOutil.setModel(new javax.swing.table.DefaultTableModel(
        new Object[][]{
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
        },
        new String[]{
            "Title 1", "Title 2", "Title 3", "Title 4"
        }
    ));
    TableOutil.setName("TableOutil"); // NOI18N
    jScrollPane1.setViewportView(TableOutil);

    jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
    jButton1.setName("jButton1"); // NOI18N
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(125, 125, 125)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(15, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(20, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>                        

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    String sql = "DELETE  FROM `car` " + "WHERE namecar=,car_manufacturing,Modelyear,carprice";

    try {
      stmt = myconnexion.ObtenirConnexion().createStatement();
      stmt.executeUpdate(sql);
    } catch (SQLException ex) {
      System.err.println(ex);
    }
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
            /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(Fenetrecarlist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(Fenetrecarlist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(Fenetrecarlist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(Fenetrecarlist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {

      public void run() {
        new Fenetrecarlist().setVisible(true);
      }
    });
  }

  // Variables declaration - do not modify                     
  private javax.swing.JTable TableOutil;
  private javax.swing.JButton jButton1;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration }                 

2 个解决方案

#1


0  

You have a colon after equal simbol, also usually in a sentence delete the condition is the primary key of the table.

你有一个冒号后等于simbol,也通常在一个句子中删除条件是表的主键。

Try this

DELETE FROM car WHERE <primary_key_column>=<value>

Regards.

#2


0  

Query syntax is invalid (, after each column)

查询语法无效(在每列之后)

String sql = "DELETE  FROM `car` " +"WHERE namecar=,car_manufacturing,Modelyear,carprice";

If you want to delete based on multiple column values use and operator in where clause.

如果要基于多个列值删除,请在where子句中使用和运算符。

String sql = "DELETE  FROM `car` WHERE namecar='some1' and car_manufacturing='some2' and Modelyear='some3' and carprice='some4'";

Edit:

String sql = "DELETE  FROM `car` WHERE namecar='some1';//single column in where clause

But you must use unique id in the where clause to delete a record. Otherwise some other records means duplicate also be deleted.

但是您必须在where子句中使用唯一ID来删除记录。否则一些其他记录意味着重复也将被删除。

#1


0  

You have a colon after equal simbol, also usually in a sentence delete the condition is the primary key of the table.

你有一个冒号后等于simbol,也通常在一个句子中删除条件是表的主键。

Try this

DELETE FROM car WHERE <primary_key_column>=<value>

Regards.

#2


0  

Query syntax is invalid (, after each column)

查询语法无效(在每列之后)

String sql = "DELETE  FROM `car` " +"WHERE namecar=,car_manufacturing,Modelyear,carprice";

If you want to delete based on multiple column values use and operator in where clause.

如果要基于多个列值删除,请在where子句中使用和运算符。

String sql = "DELETE  FROM `car` WHERE namecar='some1' and car_manufacturing='some2' and Modelyear='some3' and carprice='some4'";

Edit:

String sql = "DELETE  FROM `car` WHERE namecar='some1';//single column in where clause

But you must use unique id in the where clause to delete a record. Otherwise some other records means duplicate also be deleted.

但是您必须在where子句中使用唯一ID来删除记录。否则一些其他记录意味着重复也将被删除。