JDBC 删除记录
2018-03-21 14:14 更新
JDBC教程 - JDBC删除记录
以下代码显示了如何从表中删除记录。
它发出delete sql命令。
DELETE FROM Person WHERE id = 1
例子
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class Main { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) throws Exception { Connection conn = null; Statement stmt = null; Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Deleting database..."); stmt = conn.createStatement(); conn = DriverManager.getConnection(DB_URL, USER, PASS); stmt = conn.createStatement(); String sql = "DELETE FROM Person WHERE id = 1"; stmt.executeUpdate(sql); stmt.close(); conn.close(); } }
示例PreparedStatement
以下代码显示如何使用Oracle JDBC驱动程序删除具有PreparedStatement的记录。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class Main { private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:YourDatabase"; private static final String DB_USER = "user"; private static final String DB_PASSWORD = "password"; public static void main(String[] argv) throws Exception { Connection dbConnection = null; PreparedStatement preparedStatement = null; Class.forName(DB_DRIVER); dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); String deleteSQL = "DELETE Person WHERE USER_ID = ?"; preparedStatement = dbConnection.prepareStatement(deleteSQL); preparedStatement.setInt(1, 1001); preparedStatement.executeUpdate(); preparedStatement.close(); dbConnection.close(); } }
以上内容是否对您有帮助:
更多建议: