How to use CRUD in Java
Create, Read, Update, and Delete (CRUD). Most applications have some kind of CRUD functionality. Maybe, most of the beginners are confused about CRUD in java. Well, Insert, Select, Update, and Delete are the SQL statements. These are examples of CRUD in Java.
INSERT Statement example
import java.sql.*; public class CRUD { public Connection connection; public Statement statement; public String sql = ""; public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("Database url","root","root"); statement = connection.createStatement(); sql = "INSERT INTO tableName(name,age,nickname) values('"+name.getText()+"','"+age.getText()+"','"+nickname.getText()+"')"; statement.executeUpdate(sql); System.out.println("Success"); } catch (Exception e) { System.out.println(e); } } }
SELECT Statement example
import java.sql.*; public class CRUD { public Connection connection; public Statement statement; public ResultSet resultset; public String sql = ""; public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("Database url","root","root"); statement = connection.createStatement(); sql = "Select * from tablename"; resultset = statement.executeQuery(sql); if(resultset.next()){ String name = resultset.getString("name"); String age = resultset.getString("age"); String nickname = resultset.getString("nickname"); System.out.println(name+" "+age+" "+nickname); } } catch (Exception e) { System.out.println(e); } } }
UPDATE Statement example
import java.sql.*; public class CRUD { public Connection connection; public Statement statement; public ResultSet resultset; public String sql = ""; public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("Database url","root","root"); statement = connection.createStatement(); sql = "UPDATE tablename set age = '21' where name = 'Kensoft'"; statement.executeUpdate(sql); System.out.println("Success"); } catch (Exception e) { System.out.println(e); } } }
DELETE Statement example
import java.sql.*; public class CRUD { public Connection connection; public Statement statement; public ResultSet resultset; public String sql = ""; public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("Database url","root","root"); statement = connection.createStatement(); sql = "DELETE tablename where name = 'Kensoft'"; statement.executeUpdate(sql); System.out.println("Success"); } catch (Exception e) { System.out.println(e); } } }
That’s how you do it.