SQL Using Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Introduction

● Java will work with virtually all database software, including Oracle and Sybase
but most commonly used is freely available MySQL database.

What is Database?

● are structured to facilitate storage, retrieval, modification and deletion of data in


conjunctions with various data-processing operations
● also called electronic database

Database Management System (DBMS)

● extracts information from the database in response to queries.

MySQL

● is a relational database management system based on SQL -Structured


Query Language.

XAMPP Installation

Step 1: Download and Install XAMPP

To download and install XAMPP, go to apachefriends downloads page, the


official link to download XAMPP from. You will see XAMPP ready to download for
cross-platform like Windows, Linux, Mac OS X. Since we are discussing How to install
XAMPP on Windows 10, therefore, we will choose the Windows option as shown below.

Step 2: Run the Installer to Install XAMPP

1. XAMPP Setup Wizard

During the installation process, you may come across warning pop-ups. But
you would probably click ‘Yes’ to start the installation process. Soon after you click on
the downloaded file, the XAMPP setup wizard will open. Now click on the ‘Next’
Button to proceed.
2. Select Components

Next, you need to check the components which you want to install and can
uncheck or leave as it is which you don’t want to install. You can see there are a few
options which are light grey in color. These are the options which are necessary to run
the software and will automatically be installed. Now click on the ‘Next’ button to
continue.

3. Select Installation Folder

Now you need to choose the folder where you want to install the XAMPP. You
can choose the default location or you can choose any location of your choice and choose
the ‘Next’ button to move ahead.
4. Bitnami for XAMPP

Now will see a window showing you information about Bitnami. Simply
click on the ‘Next’ button to move further.

5. Ready to Install

Now you’ll see another window with a message “Setup is now ready to begin installing
XAMPP on your computer” like shown below. You just have to hit the ‘Next’ button to
proceed.
6. Welcome to XAMPP Wizard

Now just be patient and wait for the installation to complete.

7. Installation Complete

Once the installation is completed, you will be asked whether you would like to start the control panel now or not, displaying the
message “Do you want to start the control panel now?” Check the box and click on the ‘Finish’ button and see if the XAMPP is
working fine.

Step 3: Select your XAMPP Install Language

As soon as you will click on the Finish button in the final step of install XAMPP process,
you will be asked to select the preferred language between English and German. It is up to
you which language you choose. After that click on the ‘Save’ button to confirm your
selected language
.

Step 4: XAMPP is now Installed, run it

If the entire process of XAMPP installation went correctly, then the control panel would
open smoothly. Now click on the ‘Start’ button corresponding to Apache and MySQL.

Check if you access php admin.

Configure MySQL to Java (Netbeans)

1. Right Click Libraries then choose “Add Library”


2. Find “MYSQL JDBC Driver” then click “Add Library”

Working with MySQL database

▪ Create MySQL Database Using Java − This explains how to create MySQL
database and tables using java.
Query:
CREATE DATABASE MilkteaOrdering

▪ Connecting to MySQL database – This is to know how to open and close a


database connection.

▪ Insert Data to MySQL Database − Once you have created your database and
tables then you would like to insert your data into created tables.
Query:
INSERT INTO `persons`(`field1`, `field2`, `field3`, `field4`) VALUES
([value-1],[value-2],[value-3],[value-4])
▪ Retrieve Data from MySQL Database − To fetch or get the records from database.
Query:
SELECT * FROM `tblname`

▪ Updating Data into MySQL Database − This part explains how to update existing
records into database.
Query:
UPDATE `persons` SET field2`=[value-2],`field3`=[value-3],`field4`=[value-4]
WHERE `field1`=[value-1]

▪ Deleting Data from MySQL Database − This part explains how to delete or purge
existing records from database
Query:
DELETE FROM `persons` WHERE `field1`=[value-1]

Create MySQL Database Using Java


import java.sql.*;
public class CreateDB {
static final String DB_URL = "jdbc:mysql://localhost:3306 /";
static final String user = "root";
static final String pass = "";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, user, pass);
Statement stmt = conn.createStatement();
){
String sql = "create database simplecrud";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Connecting to MySQL database
To connect Java application with the MySQL database, we need to follow 5
following steps.

1. Driver class: The driver class for the MySQL database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the MySQL database is
jdbc:mysql://localhost:10080/simplecrud where jdbc is the API, MySQL is the database,
localhost is the server name on which MySQL is running, we may also use IP address,
10080 is the port number and simplecrud is the database name. We may use any database,
in such case, we need to replace the simplecrud with our database name.
3. Username: The default username for the MySQL database is root.
4. Password: It is the password given by the user at the time of installing the MySQL
database. There is no default password in MySQL.

package used for SQL


import java.sql.*;

Example code:
import java.sql.*;
public class DatabaseConnection {
private Connection con;

private static DatabaseConnection dbc;


private DatabaseConnection(){

try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
con
=DriverManager.getConnection("jdbc:mysql://localhost:3306/simplecrud","root","");
System.out.println("Connection Established");
} catch (Exception ex) {
System.out.println(ex);
}
}

public static DatabaseConnection getDatabaseConnection()


{
if(dbc==null)
{
dbc = new DatabaseConnection();

}
return dbc;
}
public static void main(String [] args)
{
new DatabaseConnection();
}

Insert Data to MySQL Database


private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
String fname =nameTextField.getText();

int age = Integer.parseInt(ageTextField.getText());

String contact =contactTextField.getText();

try
{
Statement smt = con.createStatement();
smt.execute("insert into persons(name,age,contact)values('"+name+"',"+age+",'"+contact+"')");
JOptionPane.showMessageDialog(this,"New record has been added!");
smt.close();
setPersonTableData();
resetData();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex);
}
private void resetData(){
nameTextField.setText("");
ageTextField.setText("");
contactTextField.setText("");
}
}
Retrieve Data from MySQL Database
private void setPersonTableData(){
try{
int rows =0;
int rowIndex=0;
Statement smt=con.createStatement();
ResultSet rs =smt.executeQuery("select* from Persons order by id asc");
if(rs.next()){
rs.last();
rows = rs.getRow();
rs.beforeFirst();
}
// System.out.println(rows);
String[][] data = new String[rows][4];
while(rs.next())
{
data[rowIndex][0]=rs.getInt(1)+"";
data[rowIndex][1]=rs.getString(2);
data[rowIndex][2]=rs.getInt(3)+"";
data[rowIndex][3]=rs.getString(4);
rowIndex++;
}
String[] cols={"ID","PERSON NAME","AGE","CONTACT"};
DefaultTableModel model =new DefaultTableModel(data,cols);
personTable.setModel(model);

rs.close();
smt.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(this,"Can not Retrieve Data");
}

}
}
Updating Data into MySQL Database
private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(personId!=0){
String name =nameTextField.getText();
int age = Integer.parseInt(ageTextField.getText());
String contact =contactTextField.getText();
try{
Statement smt= con.createStatement();
smt.execute("update persons set name='"+name+"',age="+age+",contact='"+contact+"' where
id="+personId);
JOptionPane.showMessageDialog(this,"Record Update");
setPersonTableData();
resetData();
personId=0;
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,"Can not Update Record");
}
}
}

private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {


resetData();
}

private void personTableMouseClicked(java.awt.event.MouseEvent evt) {


try
{
personId=Integer.parseInt(personTable.getValueAt(personTable.getSelectedRow(),0).toString());
Statement smt =con.createStatement();
ResultSet rs=smt.executeQuery("select* from persons where id="+personId);
if(rs.next()){
nameTextField.setText(rs.getString(2));
ageTextField.setText(rs.getInt(3)+"");
contactTextField.setText(rs.getString(4));
}
rs.close();
smt.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex);
}
}
Deleting Data from MySQL Database
private void deletetButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(personId!=0){
try
{
Statement smt=con.createStatement();
smt.execute("delete from persons where id="+personId);
JOptionPane.showMessageDialog(this,"Record Deleted");
setPersonTableData();
resetData();
personId=0;
}
catch(Exception ex){
JOptionPane.showMessageDialog(this,"Can Not Delete Record");
}
}
}
Whole Coding

package simplecrud;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class MainFrame extends javax.swing.JFrame {

private Connection con;


private int personId;
public MainFrame() {
initComponents();
DatabaseConnection dbc= DatabaseConnection.getDatabaseConnection();
con = dbc.getConnection();
setPersonTableData();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel2 = new javax.swing.JPanel();


jLabel1 = new javax.swing.JLabel();
nameTextField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
ageTextField = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
contactTextField = new javax.swing.JTextField();
jPanel1 = new javax.swing.JPanel();
submitButton = new javax.swing.JButton();
updateButton = new javax.swing.JButton();
deletetButton = new javax.swing.JButton();
resetButton = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
personTable = new javax.swing.JTable();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Personal Detail"));
jPanel2.setLayout(new java.awt.GridLayout(3, 2, 20, 20));

jLabel1.setText("Name");
jPanel2.add(jLabel1);

nameTextField.setName(""); // NOI18N
jPanel2.add(nameTextField);

jLabel2.setText("Age");
jPanel2.add(jLabel2);
jPanel2.add(ageTextField);

jLabel3.setText("Contact");
jPanel2.add(jLabel3);
jPanel2.add(contactTextField);

jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
jPanel1.setLayout(new java.awt.GridLayout(1, 4, 10, 0));

submitButton.setText("Submit");
submitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitButtonActionPerformed(evt);
}
});
jPanel1.add(submitButton);

updateButton.setText("Update");
updateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateButtonActionPerformed(evt);
}
});
jPanel1.add(updateButton);

deletetButton.setText("Delete");
deletetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deletetButtonActionPerformed(evt);
}
});
jPanel1.add(deletetButton);
resetButton.setText("Reset");
resetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resetButtonActionPerformed(evt);
}
});
jPanel1.add(resetButton);

jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

personTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
personTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
personTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(personTable);

javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);


jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
.addContainerGap())
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addContainerGap())
);

setSize(new java.awt.Dimension(564, 571));


setLocationRelativeTo(null);
}// </editor-fold>

private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {


String name =nameTextField.getText();
int age = Integer.parseInt(ageTextField.getText());
String contact =contactTextField.getText();

try
{
Statement smt = con.createStatement();
smt.execute("insert into persons(name,age,contact)values('"+name+"',"+age+",'"+contact+"')");
JOptionPane.showMessageDialog(this,"New record has been added!");
smt.close();
setPersonTableData();
resetData();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex);
}

private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {


if(personId!=0){
String name =nameTextField.getText();
int age = Integer.parseInt(ageTextField.getText());
String contact =contactTextField.getText();
try{
Statement smt= con.createStatement();
smt.execute("update persons set name='"+name+"',age="+age+",contact='"+contact+"' where id="+personId);
JOptionPane.showMessageDialog(this,"Record Update");
setPersonTableData();
resetData();
personId=0;
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,"Can not Update Record");
}
}
}

private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {


resetData();
}

private void personTableMouseClicked(java.awt.event.MouseEvent evt) {


try
{
personId=Integer.parseInt(personTable.getValueAt(personTable.getSelectedRow(),0).toString());
Statement smt =con.createStatement();
ResultSet rs=smt.executeQuery("select* from persons where id="+personId);
if(rs.next()){
nameTextField.setText(rs.getString(2));
ageTextField.setText(rs.getInt(3)+"");
contactTextField.setText(rs.getString(4));
}
rs.close();
smt.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this,ex);
}
}

private void deletetButtonActionPerformed(java.awt.event.ActionEvent evt) {


if(personId!=0){
try
{

Statement smt=con.createStatement();
smt.execute("delete from persons where id="+personId);
JOptionPane.showMessageDialog(this,"Record Deleted");
setPersonTableData();
resetData();
personId=0;
}
catch(Exception ex){
JOptionPane.showMessageDialog(this,"Can Not Delete Record");
}
}
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JTextField ageTextField;
private javax.swing.JTextField contactTextField;
private javax.swing.JButton deletetButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField nameTextField;
private javax.swing.JTable personTable;
private javax.swing.JButton resetButton;
private javax.swing.JButton submitButton;
private javax.swing.JButton updateButton;
// End of variables declaration
private void resetData(){
nameTextField.setText("");
ageTextField.setText("");
contactTextField.setText("");
}

private void setPersonTableData(){


try{
int rows =0;
int rowIndex=0;
Statement smt=con.createStatement();
ResultSet rs =smt.executeQuery("select* from Persons order by id asc");
if(rs.next()){
rs.last();
rows = rs.getRow();
rs.beforeFirst();
}
// System.out.println(rows);
String[][] data = new String[rows][4];
while(rs.next())
{
data[rowIndex][0]=rs.getInt(1)+"";
data[rowIndex][1]=rs.getString(2);
data[rowIndex][2]=rs.getInt(3)+"";
data[rowIndex][3]=rs.getString(4);
rowIndex++;
}
String[] cols={"ID","PERSON NAME","AGE","CONTACT"};
DefaultTableModel model =new DefaultTableModel(data,cols);
personTable.setModel(model);

rs.close();
smt.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(this,"Can not Retrieve Data");
}

}
}

You might also like