APM Welcome, APM North West Network Conference, Synergies Across Sectors
Chapter vii(accessing databases with jdbc)
1.
2. 1. Set: ODBC driver for JDBC connections
2. Connects: to Access database file named
3. Import the classes to connect to the database
4. Create a Statement object to execute the SQL query
5. Cleanup after finishing the job
3. import java.sql.*;
public class TestDB {
public static void main(String[] args) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=dbCustomer.mdb;";
Connection conn=DriverManager.getConnection(database,"","");
Statement s=conn.createStatement();
for(int i=1;i<=10;i++){
String addRow="INSERT INTO tbCustomer Values(" + i + ",'Dara','M','SiemReap','1/2/1920','012 33 44 55');";
s.execute(addRow);}
String deleteRow="Delete From tbCustomer where CustID=1;";
s.execute(deleteRow);
String updateRow="Update tbCustomer Set CustName='Lola', Gender='F',Address='Siem Reap',
DOB='1/2/1920',PhoneNo='010220033' Where CustID=2;" ;
s.execute(updateRow);
String selTable="SELECT* FROM tbCustomer;";
s.execute(selTable);
s.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}}
Notes de l'éditeur
/**
* File: databaseCon.java
* Tiltle: Database Connection Using MS Access
* Author: http://java-program-sample.blogspot.com/
*/
//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class TestConnect1 extends JFrame implements ActionListener {
//Initializing components
private JButton connect;
private JTextField confirmation;
Connection con;
Statement st;
ResultSet rs;
String db;
//Setting up GUI
public TestConnect1() {
//Setting up the Title of the Window
super("MS Access Connection");
//Set Size of the Window (WIDTH, HEIGHT)
setSize(250,95);
//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Constructing Components
connect = new JButton("Test Connection");
confirmation = new JTextField(20);
//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);
//Setting up the container layout
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
pane.setLayout(flow);
//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=database.mdb;";
con = DriverManager.getConnection(db,"","");
st = con.createStatement();
confirmation.setText("Successfully Connected to Database");
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
//Adding Event Listener to the button "Connect"
connect.addActionListener(this);
//Adding components to the container
pane.add(confirmation);
pane.add(connect);
/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
}
//Creating an event to the JButton "Connect"
public void actionPerformed(ActionEvent event) {
try {
if(event.getSource() == connect ) {
//Adding values on the database field "confirm" and "confirm_to"
String insert = "insert into Confirm (confirm, confirm_to) values ('"+confirmation.getText()+"','"+confirmation.getText()+"')";
st.execute(insert); //Execute the sql
//This will display if the connection and the insertion of data to the database is successful.
confirmation.setText("Test Successful");
//Display what is in the database
rs=st.executeQuery("select * from Confirm");
while(rs.next()) {
System.out.println(rs.getString("confirm"));
}
}
}catch(Exception e) {
JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
}
//Main Method
public static void main (String[] args) {
TestConnect1 pjtf = new TestConnect1(); }
}