以下代碼顯示了如何從表中刪除記錄。
它發(fā)出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(); } }
以下代碼顯示如何使用Oracle JDBC驅(qū)動(dòng)程序刪除具有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(); } }
更多建議: