The Program below is a very short, easy-to-understand java code that allows the user to add data to the database. The program is capable of detecting connection errors and input errors. You can download the whole program below including the database to properly test:
Download: addItemToDatabase.rar
Code:
/**
* File: addItemToDatabase.java
* Tiltle: Adding Data to the Database
* Author: http://java-code-complete.blogspot.com/
*/
//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class addItemToDatabase extends JFrame {
//Initializing Components
private JTextField inputs[];
private JButton add, reset;
private JLabel labels[];
private String fldLabel[] = {"First Name: ","Middle Name: ","Family Name: ","Age: "};
private JPanel p1;
Connection con;
Statement st;
ResultSet rs;
String db;
//Setting up GUI
public addItemToDatabase() {
//Setting up the Title of the Window
super("Adding Data to the Database");
//Set Size of the Window (WIDTH, HEIGHT)
setSize(300,180);
//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Constructing Components
inputs = new JTextField[4];
labels = new JLabel[4];
add = new JButton("Add");
reset = new JButton("Reset");
p1 = new JPanel();
//Setting Layout on JPanel 1 with 5 rows and 2 column
p1.setLayout(new GridLayout(5,2));
//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);
//Setting up the container layout
GridLayout grid = new GridLayout(1,1,0,0);
pane.setLayout(grid);
//Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
con = DriverManager.getConnection(db,"","");
st = con.createStatement();
JOptionPane.showMessageDialog(null,"Successfully Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
//Constructing JLabel and JTextField using "for loop" in their desired order
for(int count=0; count<inputs.length && count<labels.length; count++) {
labels[count] = new JLabel(fldLabel[count]);
inputs[count] = new JTextField(20);
//Adding the JLabel and the JTextFied in JPanel 1
p1.add(labels[count]);
p1.add(inputs[count]);
}
//Implemeting Even-Listener on JButton add
add.addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
if (inputs[0].getText().equals("") || inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null || inputs[1].getText() == null || inputs[2].getText() == null)
JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
else
try {
String add = "insert into person (firstName,middleName,familyName,age) values ('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].getText()+")";
st.execute(add); //Execute the add sql
Integer.parseInt(inputs[3].getText()); //Convert JTextField Age in to INTEGER
JOptionPane.showMessageDialog(null,"Item Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
}catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Please enter an integer on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
}catch (Exception ei) {
JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a number on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
}
}
}
);
//Implemeting Even-Listener on JButton reset
reset.addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
inputs[0].setText(null);
inputs[1].setText(null);
inputs[2].setText(null);
inputs[3].setText(null);
}
}
);
//Adding JButton "add" and "reset" to JPanel 1 after the JLabel and JTextField
p1.add(add);
p1.add(reset);
//Adding JPanel 1 to the container
pane.add(p1);
/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
}
//Main Method
public static void main (String[] args) {
addItemToDatabase aid = new addItemToDatabase();
}
}
Important Part of the Program:
//Implemeting Even-Listener on JButton add
add.addActionListener(
new ActionListener() {
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
if (inputs[0].getText().equals("") || inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null || inputs[1].getText() == null || inputs[2].getText() == null)
JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
else
try {
String add = "insert into person (firstName,middleName,familyName,age) values ('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].getText()+")";
st.execute(add); //Execute the add sql
Integer.parseInt(inputs[3].getText()); //Convert JTextField Age in to INTEGER
JOptionPane.showMessageDialog(null,"Item Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
}catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Please enter an integer on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
}catch (Exception ei) {
JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a number on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
}
}
}
);
Feel free to comment if the program doesn't work or if you have questions about the program. It has been tested many time so it runs perfectly.
No comments:
Post a Comment