Java sql删除行

时间:2014-02-04 04:13:14

标签: java sql database sql-delete

您好我试图从我的数据库中删除一行。我没有错,但它什么也没做,任何帮助或建议都会很棒!

 public static void DeleteRow(String name)
  {
     try 
     {  
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, username, password);

        PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = " + name + ";");
        st.executeUpdate(); 
     }
     catch(Exception e)
     {
         System.out.println(e);
     }
}

6 个答案:

答案 0 :(得分:16)

我猜名称是DB中的varchar类型,所以这样做

PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = '" + name + "';");

将名称括在单引号'

这也不是你使用的方式不是使用Preparedstatement的正确方法

我们采用以下方式

PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate(); 

Proper PreparedStatement之后的完整代码

public static void DeleteRow(String name)
  {
 try 
 {  
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate(); 

 }
 catch(Exception e)
 {
     System.out.println(e);
 }
}

答案 1 :(得分:1)

你永远不应该在Java中使用字符串连接创建SQL语句,它将容易受到sql注入的攻击。请这样做。

String selectSQL = "DELETE FROM Table WHERE name = ?";
connection.prepareStatement(selectSQL);
preparedStatement.setString(1, name);

答案 2 :(得分:1)

          Class.forName("oracle.jdbc.driver.OracleDriver");
          Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "MANASH_APPN","MANASH");
          PreparedStatement ps = con.prepareStatement("delete from EMP21 where empid = ?");
           ps.setInt(1,90);
           ps.executeUpdate();
          con.commit();
          System.out.println("Records Delete Successfully....");
         con.close();

答案 3 :(得分:0)

必须关闭每个打开的连接,否则它将无法实现,也不会显示任何错误。第一次吸取教训。

public static void DeleteRow(String name)
  {
     try 
     {  
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, username, password);

        PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = " + name + ";");
        st.executeUpdate(); 
        connection.close();
     }
     catch(Exception e)
     {
         System.out.println(e);
     }
}

希望这有帮助

答案 4 :(得分:0)

试试这个兄弟。使用Statement

Statement stmt = connection.createStatement();
String SQL = "DELETE FROM Table WHERE name = '"+name+"'";
stmt.executeUpdate(SQL);

答案 5 :(得分:-1)

这会奏效 String del =" DELETE FROM table WHERE name =('" + name +"')";

:)