Java sql删除行

g2ieeal7  于 2023-01-11  发布在  Java
关注(0)|答案(6)|浏览(127)

你好,我正在尝试从我的数据库中删除一行。我没有得到任何错误,但它是什么也不做,任何帮助或建议将是伟大的!

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);
    }
}
3pvhb19x

3pvhb19x1#

我猜name在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(); 

// your full code after 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);
    }
}
ukxgm1gy

ukxgm1gy2#

你不应该在Java中创建一个带有字符串连接的SQL语句,它很容易受到SQL注入的攻击。请这样做。

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

vnzz0bqm3#

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();
3df52oht

3df52oht4#

试试这个bro. use语句

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

whitzsjs5#

每个打开的连接都必须关闭,否则它将不会实现,也不会显示错误。

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);
    }
}

希望这能帮上忙

jutyujz0

jutyujz06#

字符串del ="从表中删除,其中名称=('"+名称+"')";
:)

相关问题