SQL Using Java
SQL Using Java
● Java will work with virtually all database software, including Oracle and Sybase
but most commonly used is freely available MySQL database.
What is Database?
MySQL
XAMPP Installation
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.
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
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.
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
.
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.
▪ Create MySQL Database Using Java − This explains how to create MySQL
database and tables using java.
Query:
CREATE DATABASE MilkteaOrdering
▪ 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]
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.
Example code:
import java.sql.*;
public class DatabaseConnection {
private Connection con;
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);
}
}
}
return dbc;
}
public static void main(String [] args)
{
new DatabaseConnection();
}
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");
}
}
}
package simplecrud;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
* 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() {
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);
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);
}
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>
rs.close();
smt.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(this,"Can not Retrieve Data");
}
}
}