Delete query in java

JavaMadeSoEasy.com (JMSE)

In this tutorial we will learn how to Execute DELETE query (DML command) using Statement’s executeUpdate method in java.

System. out .println( «numberOfRowsDeleted background-color: transparent; color: black; font-family: Consolas; font-size: 13.333333333333332px; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;»> + numberOfRowsDeleted);

Must read : java.sql.Statement — using executeUpdate and executeQuery methods CREATE , SELECT , INSERT , UPDATE

java.sql.PreparedStatement — using executeUpdate and executeQuery methods — CREATE , SELECT , INSERT , UPDATE and DELETE

(Also must know : delete is a DML(Data Manipulation Language) command, queries are not committed automatically in database )

We may stop connection from doing auto-commits by setting auto-commit to false using > con.setAutoCommit(false);

Also, We may set connection back to default behavior of doing auto-commit by using > con.setAutoCommit(true) or simply using con.setAutoCommit();

If any transaction goes wrong than we may halt execution further related transactions before calling con.commit() and call con.rollback() in catch block.

NOTE : Statement is suitable for executing DDL commands — create, drop, alter and truncate. This article demonstrates that Statement can also be used to serve the purpose.

We must prefer PreparedStatement , as it is suitable for executing DML commands — SELECT , INSERT , UPDATE and DELETE .

So, in this tutorial we learned how to Execute DELETE query (DML command) using Statement’s executeUpdate method in java.

java.sql.PreparedStatement — using executeUpdate and executeQuery methods — CREATE , SELECT , INSERT , UPDATE and DELETE

Difference between CLOB and CLOB data type in Oracle

JDBC Transactions — commit and rollback(TCL command) — using PreparedStatement

Execute database STORED PROCEDURE — IN parameter , OUT parameter and IN OUT parameter || call FUNCTION from java

Источник

A Java MySQL DELETE example

Here’s a Java MySQL DELETE example, demonstrating how to issue a SQL DELETE command from your Java source code.

A simple MySQL database table

The first thing we’ll need is an example MySQL database table to work with. To keep it simple — but also show several different data types — I created the following MySQL database table:

create table users ( id int unsigned auto_increment not null, first_name varchar(32) not null, last_name varchar(32) not null, date_created timestamp default now(), is_admin boolean, num_points int, primary key (id) );

A few of these fields are a little contrived, but I wanted to show several different data types in one table, so this is what I came up with. (In particular, the field «num_points» is a little unusual. I made it up so I could show an int data type in this table, and I was thinking of those websites where points are awarded for giving correct answers.)

Other than that, this MySQL database table is relatively normal, though it is greatly simplified.

An example MySQL SELECT statement

Before looking at the Java source code, if I now execute this SQL query from the MySQL command prompt:

I currently see this output:

+----+------------+-----------+---------------------+----------+------------+ | id | first_name | last_name | date_created | is_admin | num_points | +----+------------+-----------+---------------------+----------+------------+ | 2 | Fred | Flinstone | 2010-06-23 00:00:00 | 0 | 6000 | | 3 | Barney | Rubble | 2010-06-23 00:00:00 | 0 | 5000 | +----+------------+-----------+---------------------+----------+------------+ 2 rows in set (0.00 sec)

This is important to see, because I’m about to delete that «Barney Rubble» data record.

Java MySQL DELETE example — source code

Given that MySQL database table, let’s assume that we just want to delete one record in this table. To do so, we just need to follow these steps:

  1. Create a Java Connection to our MySQL database.
  2. Create a SQL DELETE query statement.
  3. Create a Java PreparedStatement for our SQL DELETE query.
  4. Set the fields on our Java PreparedStatement object.
  5. Execute our Java PreparedStatement .
  6. Close our Java MySQL database connection.
  7. Catch any SQL exceptions that may come up during the process.

I’ve tried to document the following Java MySQL DELETE example so you can see these steps. Note that in this example my MySQL database username is «root», my password is blank, and the MySQL database is running on the same computer where this program is run, so the database host name is «localhost».

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; /** * A Java MySQL DELETE example. * Demonstrates the use of a SQL DELETE statement against a * MySQL database, called from a Java program, using a * Java PreparedStatement. * * Created by Alvin Alexander, http://devdaily.com */ public class JavaMysqlDeleteExample < public static void main(String[] args) < try < // create the mysql database connection String myDriver = "org.gjt.mm.mysql.Driver"; String myUrl = "jdbc:mysql://localhost/test"; Class.forName(myDriver); Connection conn = DriverManager.getConnection(myUrl, "root", ""); // create the mysql delete statement. // i'm deleting the row where the id is "3", which corresponds to my // "Barney Rubble" record. String query = "delete from users where PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setInt(1, 3); // execute the preparedstatement preparedStmt.execute(); conn.close(); >catch (Exception e) < System.err.println("Got an exception! "); System.err.println(e.getMessage()); >> >

Java MySQL DELETE example — discussion

As noted in the Java MySQL DELETE source code, this SQL DELETE query is hard-wired to delete the row in the database where the «id» column has a value of «3». I know from looking at my database that this is the record corresponding to the «Barney Rubble» data. In a real-world program, you’ll likely have the id for the user record you want to delete, so your SQL DELETE query will look very similar to the one shown here, except you’ll have a variable in the place where I have hard-coded the number three.

After this query runs, you can verify that it worked by looking at the data from the MySQL command prompt, running a SELECT query like this:

where you will see some output like this:

+----+------------+-----------+---------------------+----------+------------+ | id | first_name | last_name | date_created | is_admin | num_points | +----+------------+-----------+---------------------+----------+------------+ | 2 | Fred | Flinstone | 2010-06-23 14:02:00 | 0 | 6000 | +----+------------+-----------+---------------------+----------+------------+ 1 row in set (0.00 sec)

Java MySQL DELETE example — summary

These days, in «real world» Java database programs I almost always use the Spring JDBC libraries to access a database, but when you’re first getting started, I think it’s important to see examples like this so you can understand how things work under the covers.

In summary, this example demonstrated:

  1. How to connect to a MySQL database.
  2. How to write a Java MySQL DELETE query (for use with a Java PreparedStatement ).
  3. How to set the desired field values for a Java PreparedStatement .
  4. How to execute the Java PreparedStatement .
  5. How to close the Java MySQL database connection.
  6. One way to confirm that our data was successfully deleted in our MySQL database.

I hope this Java MySQL DELETE example (using a Java PreparedStatement ) makes sense. As usual, if you have any questions or comments about this example, just use the Comment form below.

Источник

Java — how to make MySQL delete query with JDBC?

Brian-Tompset

In Java it is possible to make SQL DELETE query with JDBC in following way.

Note: read this article to know how to download and install JDBC driver proper way.

1. DELETE query with JDBC example

Note: this approach prevents of SQL Injection attack.

package com.dirask.examples; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class Program < private static final String DB_NAME = "test"; private static final String DB_HOST = "127.0.0.1"; // 'localhost' private static final String DB_USER = "root"; private static final String DB_PASSWORD = "root"; private static final String DB_URL = "jdbc:mysql://" + DB_HOST + "/" + DB_NAME + "?serverTimezone=UTC"; public static void main(String[] args) throws ClassNotFoundException < String sql = "DELETE FROM `users` WHERE `name` = ?"; try ( // gets connection with database Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); // sends queries and receives results PreparedStatement statement = connection.prepareStatement(sql); ) < // this way to prevent sql injection statement.setString(1, "John"); int count= statement.executeUpdate(); System.out.print("Number of deleted rows is " + count + "."); >catch (SQLException e) < // some logic depending on scenario // maybe LOGGER.log(e.getMessage()) and "result false" e.printStackTrace(); >> >
Number of deleted rows is 1.

Database state after SQL DELETE query with PDO class - PHP / MySQL.

2. Data base preparation

CREATE TABLE `users` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(100) NOT NULL, `role` VARCHAR(15) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB;
INSERT INTO `users` (`name`, `role`) VALUES ('John', 'admin'), ('Chris', 'moderator'), ('Kate', 'user'), ('Denis', 'moderator');

See also

Источник

Удаление объекта

Наконец разберем удаление объекта. В принципе удалять объекты из базы очень просто, но как говориться, есть нюансы. И таких нюансов аж шесть:

  • Удаление с помощью метода remove()
  • Удаление за компанию
  • Удаление по Orphan
  • Удаление с помощью JPQL
  • Удаление через NativeQuery
  • softDeleted()

И начнем мы с самого очевидного решения — вызова метода remove() .

 User user = new User(); user.setName("Колян"); session.persist(user); //добавляем объект в базу session.flush(); session.clear(); //закрываем сессию user = (User) session.find(User.class, user.getId() ); //заново получаем объект из базы session.remove(user); session.flush(); session.clear(); //закрываем сессию //тут объект реально удален. 

Реальная операция в базе будет выполнена после вызова метода flush() или закрытия транзакции.

Каскадное удаление

Помнишь, когда мы изучали SQL, то зависимым таблицам можно было прописывать CONSTRAINT. И одна из них записывалась так:

 CONSTRAINT ONDELETE REMOVE

Смысл ее был в том, что если у нас есть таблица, которая содержит дочерние сущности, то при уделении сущности-родителя нужно удалить все ее дочки.

Допустим, мы где-то храним персональную информацию пользователя и настроили CONSTRAINT в базе так, чтобы при удалении пользователя эти данные тоже удалялись. Тогда нам нужно просто удалить родительский объект и все дочерние объекты будут удалены на уровне базы:

 User user = new User(); UserPrivateInfo info = new UserPrivateInfo(); user.setPrivateInfo(info); session.persist(user); //добавляем объект в базу, также в базу сохранится и объект info session.flush(); session.clear(); //закрываем сессию user = (User) session.find(User.class, user.getId() ); //заново получаем объект из базы session.remove(user); session.flush(); session.clear(); //закрываем сессию //тут объекты user и info реально удалены из базы. 

Удаление по Orphan

Также есть еще один тип удаления, который называют удаление по Orphan. Он чем-то похож на предыдущий вариант. Дочерняя сущность удаляется, когда разрывается ее связь с родительской сущностью. При этом родительская сущность обычно не удаляется.

Допустим, у нас есть пользователь, а у него есть список сообщений:

 User user = new User(); UserMessage message = new UserMessage(); user.getMessageList().add(message); session.persist(user); //добавляем объект в базу, также в базу сохранится и объект message session.flush(); session.clear(); //закрываем сессию user = (User) session.find(User.class, user.getId() ); //заново получаем объект из базы UserMessage message2 = user.getMessageList().get(0); //получаем сообщение пользователя user.getMessageList().remove(message2); //удаляем сообщение из списка session.flush(); session.clear(); //закрываем сессию //тут объект message2 реально удален из базы 

Также есть важный нюанс, если мы хотим, чтобы Hibernate реализовывал такое поведение, его нужно явно указать при связывании двух сущностей с помощью аннотаций:

 @Entity public class User < @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) private ListmessageList = new ArrayList(); > 

Удаление через JPQL

Еще один интересный способ удалить объект – это написать запрос на HQL (или JPQL). Только не забудь в конце вызвать метод executeUpdate() , а не то Hibernate создает read-only транзакцию и никакого удаления у тебя не выйдет.

 User user = new User(); session.persist(user); //добавляем объект в базу session.flush(); session.clear(); //закрываем сессию session.createQuery("delete from User where .setParameter("id", user.getId()) .executeUpdate(); 

Изменение в базе никак не изменит существующие Entity-объекты.

Удаление через NativeQuery

Аналогично можно удалить и через вызов NativeQuery.

 User user = new User(); session.persist(user); //добавляем объект в базу session.flush(); session.clear(); //закрываем сессию session.createNativeQuery("DELETE FROM user WHERE .setParameter("id", user.getId()) .executeUpdate(); 

Изменение в базе никак не затронет существующие Entity-объекты.

Мягкое удаление

Иногда вместо удаления данных в базе бывает удобно просто пометить их как удаленные. Такие данные могут потом участвовать в различных сценариях. Во-первых, такое удаление легко обратимо – строки можно опять пометить как живые.

Во-вторых, такие удаленные данные полезно “складывать в архив”, ведь бывают случаи, когда поведение сервера регулируется законодательством и тому подобное. Однако, если ты будешь помечать твои данные как удаленные, то только ты будешь знать, что они удалены. Hibernate же по-прежнему будет находить эти данные, а также использовать их при сортировке.

Поэтому создатели Hibernate придумали специальную аннотацию, с помощью которой можно было бы помечать объекты как живые. Пример:

 @Entity @Where(clause = "DELETED = 0") //во всех WHERE будет добавляться “AND DELETED = 0” public class User < // маппинг полей @Column(name = "DELETED") // если значение в колонке DELETED == 0, то запись жива, если 1 - мертва private Integer deleted = 0; //геттеры и сеттеры public void softDeleted() < this.deleted = 1; //помечаем запись как мертвую >> 

Чтобы пометить объект как удаленный нужно просто вызвать у него метод softDeleted() :

 User user = new User(); session.persist(user); //добавляем объект в базу session.flush(); session.clear(); //закрываем сессию user = (User) session.find(User.class, user.getId() ); //заново получаем объект из базы user.softDeleted(); //помечаем объект как удаленный session.flush(); session.clear(); //закрываем сессию //больше этот объект не будет находиться через Hibernate 

Источник

Читайте также:  Variable not exist php
Оцените статью