如何从Java中删除数据库表中的行

时间:2014-12-01 11:58:09

标签: java database

我正在尝试用Java开发一个简单的Java DVD库控制台应用程序。我创建了一个包含DVD列表的数据库表。我已经成功地将数据库中的新DVD添加到数据库中,但我正在努力从数据库中删除一行。当我使用SQL语句选择行(第7行)然后运行'rs.delete'行时,我得到以下异常: -

  

无效的游标状态 - 没有当前行。

以下是我的数据库表: -

ID   Film Name    Genre   Rating
-------------------------------
1    Robocop      Sci-fi  18
2    Terminator   Sci-fi  18
3    Alien        Sci-fi  18
4    Big Fish     Fantasy PG
5    The Pianist  Drama   18
6    Total Recall  Sci-fi 18
7    Carnage Comedy       18

下面是我的代码的副本。请有人帮忙吗?

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dvdlibrary;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import java.util.Scanner;
/**
*
* @author Andy
*/
public class DVDLibrary {

    Connection con;
    Statement stmt;
    ResultSet rs;

    String selection = "";
    int id_num =0;
    String film_name ="";
    String genre ="";
    String rating="";


        public DVDLibrary()
        {
            DoConnect();
        }

        public void DoConnect() { 

            try
            {
                String host = "jdbc:derby://localhost:1527/DVDLibrary";
                String username = "andyshort";
                String password = "Pa55word";`enter code here`

                con = DriverManager.getConnection(host, username, password);
                stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

                String SQL = "SELECT * FROM ANDYSHORT.DVDS";

                rs = stmt.executeQuery(SQL);

                /*
                System.out.println("ID   Film Name   Genre   Rating");
                System.out.println("-------------------------------");

                while (rs.next())                
                {   
                    int id_col = rs.getInt("ID");
                    String film_name_col = rs.getString("Film_Name");
                    String genre_col = rs.getString("Genre");
                    String rating_col = rs.getString("Rating");

                    String p = id_col + "    " + film_name_col + "    " + genre_col + "    " + rating_col;

                    System.out.println(p);     
                    //System.out.format("%32s%10d%16s", id_col , film_name_col, genre_col, rating_col);
                }
                */
            }
            catch (SQLException err)
            {
                System.out.println(err.getMessage());
            }

        }

        public void GetUserInput()
        { 
            System.out.println(); 
            System.out.println("What would you like to do? Choose one of the following options.");
            System.out.println("1. Display DVD library list");
            System.out.println("2. Add a new film to database.");        
            System.out.println("3. Delete a film from the database.");               

            System.out.println();  

            Scanner user_option_selection = new Scanner(System.in);

            selection = user_option_selection.next();

            if(selection.equalsIgnoreCase("1"))
            {
                DisplayDVDList();
            }
            else if(selection.equalsIgnoreCase("2"))
            {
                AddRecord();
            }
            else if(selection.equalsIgnoreCase("3"))
            {
                DeleteRecord();
            }
            else
            {
                System.out.println("Incorrect option entered. Please try again.");   
            }
        }

        public void DisplayDVDList()
        {
             try
            {                
                String SQL = "SELECT * FROM ANDYSHORT.DVDS";
                rs = stmt.executeQuery(SQL);    

                System.out.println("ID   Film Name   Genre   Rating");
                System.out.println("-------------------------------");

                while (rs.next())                
                {   
                    int id_col = rs.getInt("ID");
                    String film_name_col = rs.getString("Film_Name");
                    String genre_col = rs.getString("Genre");
                    String rating_col = rs.getString("Rating");

                    String p = id_col + "    " + film_name_col + " " + genre_col + " " + rating_col;

                    System.out.println(p);     
                    //System.out.format("%32s%10d%16s", id_col , film_name_col, genre_col, rating_col);
                }
            }
            catch (SQLException err)
            {
                System.out.println(err.getMessage());
            }
            GetUserInput();
        }

        public void AddRecord()
        {
            Scanner new_film_details = new Scanner(System.in);

            System.out.println("Please enter film name: ");
            film_name = new_film_details.next();

            System.out.println("Please enter film genre: ");
            genre = new_film_details.next();

            System.out.println("Please enter film rating: ");
            rating = new_film_details.next();

            try
            {
                rs.last();

                id_num = rs.getRow();
                id_num = id_num + 1;

                rs.moveToInsertRow();

                rs.updateInt("ID", id_num);
                rs.updateString("FILM_NAME", film_name);
                rs.updateString("GENRE", genre);
                rs.updateString("RATING", rating);

                rs.insertRow();

                //stmt.close( );
                //rs.close( );
            }
            catch(SQLException err)
            {
                System.out.println(err.getMessage());
            }
            GetUserInput();
        }



        public void DeleteRecord()
        {
            String id = "";
            Scanner id_of_film_to_delete= new Scanner(System.in);

            System.out.println("Enter ID of film you want to delete.");
            id = id_of_film_to_delete.next();    
            int idInt = Integer.parseInt(id);

            try
            {
                stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                String sql = "SELECT * FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
                rs = stmt.executeQuery(sql);

                rs.deleteRow();

            }
            catch(SQLException err)
            {
                System.out.println(err.getMessage());
            }
            GetUserInput();
        }



    }   

4 个答案:

答案 0 :(得分:4)

直接使用此查询

 "DELETE FROM ANDYSHORT.DVDS WHERE ID =" + idInt;

答案 1 :(得分:2)

String sql = "DELETE FROM ANDYSHORT.DVDS WHERE ID=?";

PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "+ idInt+");

int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println(" delete successfully!");
}

答案 2 :(得分:0)

使用预准备语句来避免SQL注入:

PreparedStatement statement;
statement = con.prepareStatement("DELETE FROM andyshort.dvds WHERE id = ?");
statement.setInt(1, idToDelete);
statement.executeUpdate();

答案 3 :(得分:0)

如果您手头有Id,可以直接使用删除查询。

String sql = "DELETE FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
stmt.executeUpdate(sql);

但是,最好使用预准备语句而不是语句来避免SQL注入攻击。

String query= "DELETE FROM ANDYSHORT.DVDS WHERE ID = ? ";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.setInt(1,idInt);
preparedStatement.executeUpdate();

如果要使用deleteRow()方法,则需要在删除行之前将光标移动到第一行。

rs.first();
rs.deleteRow();