jdbcでMySQLのテーブルデータを削除する方法は?
MySQLテーブルのデータを削除するためのJDBCの手順は次のとおりです:1. データベース・ドライバをロードする:MySQLのバージョンに合った適切なドライバを選択し、Class.forName()メソッドを使用してドライバをロードします。例:
Class.forName("com.mysql.jdbc.Driver");
2. データベース接続を確立する:DriverManager.getConnection()メソッドを使用し、接続URL、ユーザー名、パスワードを渡してデータベース接続オブジェクトを取得します。例:
String url = "jdbc:mysql://localhost:3306/database_name"; String username = "root"; String password = "password"; Connection connection = DriverManager.getConnection(url, username, password);
3. ステートメントオブジェクトを作成する:ConnectionオブジェクトのcreateStatement()メソッドを使用して、ステートメントオブジェクトを作成します。例えば、
Statement statement = connection.createStatement();
4. SQL文を書く:DELETE文を使用してテーブルのデータを削除します。例えば:
String sql = "DELETE FROM table_name WHERE condition";
table_nameとは、データを削除するテーブルの名前であり、conditionは削除条件です。5. SQL文を実行する:StatementオブジェクトのexecuteUpdate()メソッドを使用してSQL文を実行します。例えば:
int rows = statement.executeUpdate(sql);
executeUpdate()メソッドは影響を受けた行数を返します。 6. データベース接続を閉じる:Connectionオブジェクトのclose()メソッドを使用してデータベース接続を閉じます。例えば、
connection.close();
完全なサンプルコードは以下の通りです:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DeleteDataExample {
public static void main(String[] args) {
try {
Class.forName(“com.mysql.jdbc.Driver”);
String url = “jdbc:mysql://localhost:3306/database_name”;
String username = “root”;
String password = “password”;
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String sql = “DELETE FROM table_name WHERE condition”;
int rows = statement.executeUpdate(sql);
System.out.println(rows + ” rows deleted”);
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
} }
database_nameはデータベース名、table_nameはテーブル名、conditionは削除条件です。例のコードのデータベース接続URL、ユーザー名、パスワード、データベース名、テーブル名、削除条件を置き換えることに注意してください。