embed MS Access database with runnable jar - java

So my aim is to make a runnable jar. I've made a program using swings which uses MS Access database to fetch records. So, I've used an absolute path to refer to the database for connection.
Now, I intend to distribute this runnable jar to other people as well. So I guess the best option would be to embed the MS Access database as well in the jar file. But I don't know how to do that. Where should I keep the database in my Project Explorer ? Should I use a relative path etc. Any form of help would be appreciable.
I've found many tutorials for using Derby database that would implement the same but none pertaining to Ms Access database. Suggestions are welcome !
This is my code:-
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class r_search extends JFrame implements ActionListener {
JFrame frame1;
JLabel l0, l1, l2;
JComboBox c1;
JButton b1;
Connection con;
ResultSet rs, rs1;
Statement st, st1;
PreparedStatement pst;
String ids;
static JTable table;
String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
String from;
r_search() {
l0 = new JLabel("Fetching Search Results...");
l0.setForeground(Color.blue);
l0.setFont(new Font("Serif", Font.BOLD, 20));
l1 = new JLabel("Search");
b1 = new JButton("submit");
l0.setBounds(100, 50, 350, 40);
l1.setBounds(75, 110, 75, 20);
b1.setBounds(150, 150, 150, 20);
b1.addActionListener(this);
setTitle("Search Executive Reports :) ");
setLayout(null);
//setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
add(l0);
add(l1);;
add(b1);
try {
Vector v = new Vector();
String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(url,"","");
/*con = DriverManager.getConnection("jdbc:oracle:thin:#mcndesktop07:1521:xe", "sandeep", "welcome");*/
st = con.createStatement();
rs = st.executeQuery("select index_name from Index1");
// Vector v = new Vector();
while (rs.next()) {
ids = rs.getString(1);
v.add(ids);
}
c1 = new JComboBox(v);
c1.setBounds(150, 110, 150, 20);
add(c1);
st.close();
rs.close();
} catch (Exception e) {
}
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
showTableData();
}
}
public void showTableData() {
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
table = new JTable();
table.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
from = (String) c1.getSelectedItem();
//String textvalue = textbox.getText();
String uname = "";
String email = "";
String pass = "";
String cou = "";
try {
/* pst = con.prepareStatement("select * from emp where UNAME='" + from + "'");*/
pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
+ "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID ) LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID "
+ " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
ResultSet rs = pst.executeQuery();
int i = 0;
while (rs.next()) {
uname = rs.getString("Section_Name");
email = rs.getString("Report_Name");
pass = rs.getString("Contact_Name");
cou = rs.getString("Link");
model.addRow(new Object[]{uname, email, pass, cou});
i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(1000, 400);
}
public static void main(String args[]) {
new r_search();
}
}

The following worked for me using Eclipse and JavaSE-1.7. Eclipse shows the following in its Package Explorer
The [folders] and files in my project folder are
[C:]
[Users]
[Gord]
[workspace]
[com.example.jartest]
[src]
[com]
[example]
[jartest]
JarTestMain.java
[resources]
JarData.mdb
The Java code in JarTestMain.java is
package com.example.jartest;
import java.io.*;
import java.nio.file.*;
import java.sql.*;
public class JarTestMain {
public static void main(String[] args) {
String mdbFileName = "JarData.mdb";
String tempDbPath = System.getenv("TEMP").replace('\\', '/') + "/" + mdbFileName;
// retrieve .mdb database from the JAR file and save to %TEMP% folder
InputStream strmIn = JarTestMain.class.getResourceAsStream("resources/" + mdbFileName);
File f = new File(tempDbPath);
try {
Files.copy(strmIn, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
// open the copy of the database in %TEMP% folder and read from its table
String connectionString =
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
"DBQ=" + tempDbPath;
try (Connection con = DriverManager.getConnection(connectionString)) {
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM Table1");
while (rs.next()) {
System.out.println(String.format(
"%d: %s",
rs.getInt("ID"),
rs.getString("TextField")));
}
rs.close();
con.close();
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
After I exported the project to a "Runnable JAR file" named JarTest.jar I was able to run it on my 32-bit Windows test machine using...
"C:\Program Files\Java\jre7\bin\java" -jar JarTest.jar
...and on my 64-bit Windows development machine via
"C:\Program Files (x86)\Java\jre7\bin\java" -jar JarTest.jar

Related

Deleting data in table (SQLite) through java (Eclipse)

as the title suggests, ive been trying to delete data in a table in my SQLite through the use of a button. I have been able to make it work on another class, but i cant seem to make it work on this specific class which i will show you.
the button is called btnDelete, and the method that loads the database and deletes it is called delete_account.
Button btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
Here's the whole code in the class just in case it is needed:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class AccSettings {
private JFrame frmAccountSett;
private JTextField txtFullname;
private JTextField txtUsername;
private JPasswordField txtPassword;
private int userid;
private String user;
/**
* Create the application.
*/
public AccSettings(String username) {
user=username;
//userid = id;
initialize();
edit_account();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAccountSett = new JFrame();
frmAccountSett.setTitle("Account Settings");
frmAccountSett.setBounds(100, 100, 450, 300);
frmAccountSett.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAccountSett.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Edit Username:");
lblUsername.setBounds(85, 62, 103, 14);
frmAccountSett.getContentPane().add(lblUsername);
txtUsername = new JTextField();
txtUsername.setBounds(229, 59, 137, 20);
frmAccountSett.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(229, 90, 137, 20);
frmAccountSett.getContentPane().add(txtPassword);
JButton btnConfirm = new JButton("Confirm Changes");
btnConfirm.setBounds(146, 164, 137, 29);
frmAccountSett.getContentPane().add(btnConfirm);
JLabel lblPassword = new JLabel("Edit Password:");
lblPassword.setBounds(85, 93, 103, 14);
frmAccountSett.getContentPane().add(lblPassword);
frmAccountSett.setVisible(true);
JButton btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
btnDelete.setBounds(299, 227, 125, 23);
frmAccountSett.getContentPane().add(btnDelete);
JButton btnBack = new JButton("<< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frmAccountSett.dispose();
}
});
btnBack.setBounds(10, 227, 103, 23);
frmAccountSett.getContentPane().add(btnBack);
JLabel lblFullname = new JLabel("Edit Fullname:");
lblFullname.setBounds(85, 31, 103, 14);
frmAccountSett.getContentPane().add(lblFullname);
txtFullname = new JTextField();
txtFullname.setColumns(10);
txtFullname.setBounds(229, 28, 137, 20);
frmAccountSett.getContentPane().add(txtFullname);
btnConfirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
update_account();
}
});
}
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
#SuppressWarnings("deprecation")
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"'"
+ "WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
//load the results
public void edit_account()
{
try {
Connection con; //create a variable for con
Database db = new Database(); //create an instance of database class
con = db.open_connection(); //set con as connection form database class
Statement st;
st = con.createStatement();
//create a statement variable
//create the query that will search the table based on similar terms
String query = "SELECT * FROM tblUsers WHERE userID=" + userid+ "";
//get the resultset of the query (rows)
ResultSet rs = st.executeQuery(query);
if (rs.next())
{
do{
txtFullname.setText(rs.getString(2));
txtUsername.setText(rs.getString(3));
txtPassword.setText(rs.getString(4));
}
while(rs.next());
}
/*
else {
JOptionPane.showMessageDialog(null, "Edit failed");
}
*/
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I believe the problem stems mostly from userID which zephyr has stated. I followed a code from another class(frmEditRef), but that class uses a JScrollPane, which when called from another class (frmMainInterface) looks like this:
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int x = table.getSelectedRow(); //get the current row
int ans = JOptionPane.showConfirmDialog(null, "Do you want to edit this record?");
if (ans == 0) {
//proceed to edit the transaction
//get the id
String id = String.valueOf(model.getValueAt(x, 0));
new EditRef(user,Integer.valueOf(id));
frmUserRef.dispose();
}
}
});
The class im trying to work with does not use JScrollPane. Therefore the coding to it would be different. Here's how it looks like from frmMainInterface:
btnAccountSett.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String id = ;
new AccSettings(user,Integer.valueOf(id));
}
});
As you can see, i have no idea what to put in after the "String id =".
I hope this explanation can get through you guys. I myself am having difficulty trying to explain something i dont even fully understand.

JAVA 1.7 and Mysql 5.7 connection

I have Java jdk1.7xxx installed and a MySQL database v5.7 too.
My database is named "mydb".
I access it from the mysql console.
However when I try to access it from my java program it makes an error "source of data unknown, or pilot name not specified". So I am missing some pilot/extra file I guess. But I did import java.sql.* at the beginning of my program..
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import java.sql.*;
import java.util.*;
public class DPIA_impacts extends JFrame {
// Labels
JLabel lb_title;
JTable tableau = null;
static JPanel p_global, p_title, p_center, p_south;
JScrollPane scroll=null;
JButton btn_Save, btn_Export;
//DefaultTableModel model;
ArrayList t1=new ArrayList();
ArrayList t2=new ArrayList();
ArrayList t3=new ArrayList();
public DPIA_impacts(){
//declarations
p_global = new JPanel();
p_title = new JPanel();
p_center = new JPanel();
p_south = new JPanel();
lb_title = new JLabel("DPIA meeting: fill the table !");
btn_Save = new JButton("Save");
btn_Export = new JButton("Export");
scroll = new JScrollPane();
// add tool tip text to the Save and Export buttons
btn_Save.setToolTipText("Save to the database Impacts table");
btn_Export.setToolTipText("Exports the contents of the Jtable to an Excel file");
// add Action Listener to the buttons
btn_Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("You clicked the button SAVE");
String url = "jdbc:mysql://localhost/mydb";
String login = "root";
String passwd = "toor";
Connection cn = null;
Statement st = null;
try {
//chargement du driver
Class.forName("com.mysql.jdbc.Driver");
// Recup connexion
cn = DriverManager.getConnection(url, login, passwd);
// Creation d'un statement
st = cn.createStatement();
String sql = "SELECT * FROM impacts";
st.executeUpdate(sql);
//instruction.executeQuery(req);
} // Try
catch (SQLException ex)
{
System.out.println("Connexion à la base de données impossible");
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
System.out.println("Pilote de connexion introuvable");
ex.printStackTrace();
//}//end catch
} finally {
try{
cn.close();
st.close();
} catch (SQLException sqle){
sqle.printStackTrace();
}
}
}});
btn_Export.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("You clicked the button EXPORT");
}
});
//add the components to the righ panels
p_title.add(lb_title);
p_center.add(scroll);
p_south.add(btn_Save, BorderLayout.WEST);
p_south.add(btn_Export, BorderLayout.EAST);
String req = "SELECT * FROM impacts";
int i =0;
Connect resultat = new Connect(req,1,"BaseDeDonnees");
// connexion a la base de donnees
}//end constructor
public static void main(String args[]) {
//Create and set up the window.
DPIA_impacts f = new DPIA_impacts();
f.setTitle("DPIA: check the impacts");
//f = new JFrame("DPIA: Impacts");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(p_title, BorderLayout.PAGE_START);
f.getContentPane().add(p_center, BorderLayout.CENTER);
f.getContentPane().add(p_south, BorderLayout.PAGE_END);
f.pack();
f.setSize(500, 300);
f.setVisible(true);
}//end main
}//end programm !
Adding the jar:
I think that in String url = "jdbc:mysql://localhost/mydb";
you forgot to write the port number.
try String url ="jdbc:mysql://127.0.0.1:3306/mydb";
UPDATE
Ok, just try this code and run it from Eclipse and not from cmd.
Also you use executeUpdate for INSERT. For SELECT you use executeQuery.
//Execute when button is pressed
System.out.println("You clicked the button SAVE");
String url = "jdbc:mysql://127.0.0.1:3306/mydb";
String login = "root";
String passwd = "toor";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
System.out.println("Connecting to database..");
try {
cn = DriverManager.getConnection(url, login, passwd);
System.out.println("Database Connected");
st = cn.createStatement();
String sql = "SELECT * FROM impacts";
rs = st.executeQuery(sql);
while (rs.next()){
//do something
}
//instruction.executeQuery(req);
} // Try
catch (SQLException ex)
{
System.out.println("Connexion à la base de données impossible");
ex.printStackTrace();
}
finally {
try{
if (cn != null ){
cn.close();
}
if (st != null ){
st.close();
}
if (rs != null ){
rs.close();
}
} catch (SQLException sqle){
sqle.printStackTrace();
}
}

Login issue in java swing

I want to create a login page but it's not working properly. When I type in a username and password and click on the Login button, nothing is happening and I am not seeing any error message.
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
public class acclogin extends JFrame {
Connection con;
Statement st;
ImageIcon bg = new ImageIcon("wb1.jpg");
JFrame f = new JFrame("User Login");
ResultSet rs;
JLabel l = new JLabel("Username");
JLabel l1 = new JLabel("Password");
JLabel l2 = new JLabel(bg);
JTextField t = new JTextField(15);
JPasswordField t1 = new JPasswordField(15);
JButton b = new JButton("Login");
public acclogin() {
frame();
}
public void frame() {
f.setSize(620, 300);
l.setBounds(10, 20, 100, 10);
t.setBounds(100, 20, 100, 20);
l1.setBounds(10, 50, 100, 80);
t1.setBounds(100, 70, 100, 20);
b.setBounds(100, 130, 100, 30);
l2.setBounds(0, 0, 600, 300);
f.add(l);
f.add(t);
f.add(l1);
f.add(t1);
f.add(b);
f.add(l2);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
LoginButton lb = new LoginButton();
b.addActionListener(lb);
}
class LoginButton implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj == b) {
try {
String user = t.getText().trim();
String pass = t1.getText().trim();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 = DriverManager.getConnection("jdbc:odbc:balogin");
Statement stat;
stat = con1.createStatement();
ResultSet rs = stat.executeQuery("select * from Table1 where user='" + user + "' and pass='" + pass + "'");
System.out.println("select * from Table1 where user='" + user + "' and pass='" + pass + "'");
int count = 0;
while (rs.next()) {
{
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "User Found,Access Granted");
ControlPanel cp1 = new ControlPanel();
cp1.display();
} else {
JOptionPane.showMessageDialog(null, "User not found");
}
}
} catch (Exception ex) {
}
}
}
}
public static void main(String args[]) {
new acclogin();
}
}
This is not exactly a solution for the problem, but this code has so many issues that you should solve before moving on.
This is what I would do:
split the code into multiple methods to take apart UI code from working with database
do not concat SQL query from strings, use prepared statement instead (omiting this could lead to an SQL injection, try login as ';DROP TABLE user;--)
usage of int count just for checking an existence of an element is confusing, you can use boolean or change SQL query to SELECT COUNT(*) ... or SELECT 1 IF EXISTS (SELECT * FROM ...)
you do not have to check the action event source, it will be always be the login button unless you assign the listener to something else
add e.printStackTrace() on catching exception
I also believe that you should use JPasswordTextField.getPassword() instead of getText()
remember closing ResultSet and Statement after use by calling .close()
try this :
Object obj = ae.getSource();
if ((JButton)obj ==(JButton)b) {
......... }

how to retrieve data from db automatic of given id?

Hi i am using swing for data retrieving i i am able to retrieve data on action perform.
but i want to retrieve data when i run this program automatic given id data retrieve from
database.
Help me Please
Thanks
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.*;
public class BankGui extends JApplet implements ActionListener{
// GUI components
JLabel lblUser, lblPass,lblnull,lbl1;
JTextField txtid;
JTextField txtUser;
JTextField txtPass;
JButton btnOk, btnClear;
// connections to MYSQL
private static Connection connection = null;
private static Statement statement = null;
private static ResultSet resultSet = null;
//public static Scanner in = new Scanner(System.in);
public void init(){
Container c = getContentPane();
c.setLayout( new FlowLayout() );
lblUser = new JLabel( "Username: " );
c.add( lblUser );
txtUser = new JTextField( 10 );
c.add( txtUser );
lblPass = new JLabel( "Password:" );
c.add( lblPass );
txtPass = new JTextField( 10 );
c.add( txtPass );
lbl1 = new JLabel( "Enter id" );
c.add( lbl1);
txtid=new JTextField(10);
c.add(txtid);
btnOk = new JButton( "OK" );
btnOk.addActionListener( this );
c.add( btnOk );
lblnull= new JLabel("");
c.add(lblnull);
}
#Override
public void actionPerformed(ActionEvent e) {
PreparedStatement stmt=null;
boolean isFound=false;
try{
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
// String sql="SELECT uname FROM users1 WHERE uname=? and pwd=?";
String sql = "SELECT * FROM users WHERE uid = '"+2+"'";
stmt=connection.prepareStatement(sql);
//stmt.getString(1,txtUser.getText());
// stmt.setString(2,txtPass.getText());
resultSet=stmt.executeQuery();
if(resultSet.next()){
isFound=true;
// String s=resultSet.getString(1);
// String s1=resultSet.getString(2);
//System.out.println(s);
txtPass.setText(resultSet.getString(1));
lblnull.setText(resultSet.getString(2));
// System.out.println(s1);
}
//
}catch(SQLException ex){
System.err.println(ex);
}finally{
if(stmt!=null){
try{
stmt.close();
}catch(Exception ex) { /* */ }
}
if(connection!=null){
try{
connection.close();
}catch(Exception ex) { /* */ }
}
}
}
static {
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception ex) {
System.err.println(ex);
}
}
}
If datatype of uid is int then your query should be
String sql = "SELECT * FROM users WHERE uid = "+2;
'2' is used for varchar datatype
In addition to #AJ answer I have some tips:
Database calls are time consuming tasks and may block the Event Dispatch Thread (a.k.a. EDT) causing the GUI become unresponsive. To avoid this issue consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing trail.
It's not a good practice ignore exceptions in a catch block: catch(Exception ex){}
Note your query is vulnerable to SQL injection attaks. To avoid this you may want to try PreparedStatement instead.
Example:
String sql = "SELECT * FROM users WHERE uid = ?";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setInt(1, 2); // see PreparedStatement.setInt(index, value)
ResultSet rs = pst.executeQuery();

dynamic Jtree from database

I have a database table named tree1, which has a table names student_details.This table has 3 columns student_name,student_details,student_phone
Now, am able to retrieve student details from the database but only in static way.
Question is when I insert a new student detail row {student_name,student_details,student_phone} I want it to show on my Jtree. Although Hashmap is the solution I am not able to understand how to use hashmap in a Jtree to create dynamic nodes.
below is the code from which I could do a static Jtree, and i want to make it dynamic. Can anyone tell me how to do this with a code sample?
package tree_try;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.Statement;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
public class SimpleTree extends JFrame
{
public Connection connect = null;
public Statement statement = null;
public Statement statement2 = null;
public Statement statement3 = null;
public Statement statement4 = null;
public Statement statement5 = null;
public Statement statement6 = null;
public ResultSet resultSet = null;
public ResultSet resultSet2 = null;
public ResultSet resultSet3 = null;
public ResultSet resultSet4 = null;
public ResultSet resultSet5 = null;
public ResultSet resultSet6 = null;
public ArrayList arrayList = new ArrayList();
public ArrayList arrayList2 = new ArrayList();
public ArrayList arrayList3 = new ArrayList();
public ArrayList arrayList4 = new ArrayList();
static String store[] = new String[10];
static String store2[] = new String[10];
static String store3[] = new String[10];
//for the panel
static String store4[] = new String[10];
static String store5[] = new String[10];
static String store6[] = new String[10];
static String store7[] = new String[10];
//for panel over
int i=0;
int i1=0;
int i2=0;
int i3=0;
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JFrame jf1 = new JFrame();
JButton jb1 = new JButton("Save");
JButton jb2 = new JButton("Cancel");
JTextField jt1= new JTextField();
JTextField jt2 = new JTextField();
JTextField jt3= new JTextField();
JTextField jt4 = new JTextField();
JLabel jl0 = new JLabel();
JLabel jl1 = new JLabel("Name : ");
JLabel jl2 = new JLabel("Adress : ");
JLabel jl3 = new JLabel("Phone Number : ");
JLabel jl4 = new JLabel("Other Deatils : ");
JLabel jl5 = new JLabel("");
public static void main(String[] args)
{
new SimpleTree();
}
public SimpleTree()
{
super("Schools database");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
//db part
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata1","suraj","suraj");
PreparedStatement statement = connect.prepareStatement("SELECT * from school_details");
PreparedStatement statement2 = connect.prepareStatement("select student_name from student_details where s_id =1");
PreparedStatement statement3 = connect.prepareStatement("select student_name from student_details where s_id =2");
//for the panel display
//PreparedStatement statement5 = connect.prepareStatement("select student_name from student_details where s_id =1");
//PreparedStatement statement6 = connect.prepareStatement("select student_name from student_details where s_id =2");
resultSet = statement.executeQuery();
while (resultSet.next())
{
String sname = resultSet.getString("school_name");
String sid = resultSet.getString("s_id");
arrayList.add(sname);
System.out.println("this is stsement one"+sname);
//arrayList.add(number);
}
resultSet2 = statement2.executeQuery();
while (resultSet2.next())
{
String user2 = resultSet2.getString("student_name");
//int number2 = resultSet2.getInt("s_id");
arrayList2.add(user2);
System.out.println("this is stsement two"+user2);
}
// System.out.println(arrayList);
resultSet3 = statement3.executeQuery();
while (resultSet3.next())
{
String user3 = resultSet3.getString("student_name");
//int number2 = resultSet2.getInt("s_id");
arrayList3.add(user3);
System.out.println("this is stsement three"+user3);
}
System.out.println("this is after statement 3 before 4");
}
catch (Exception e2)
{
e2.printStackTrace();
}
//
Iterator it = arrayList.iterator();
while (it.hasNext())
{
store[i]= (String) it.next();
i++;
//System.out.println(it.next());
}
Iterator it2 = arrayList2.iterator();
while (it2.hasNext())
{
store2[i1]= (String) it2.next();
i1++;
//System.out.println(it.next());
}
Iterator it3 = arrayList3.iterator();
while (it3.hasNext())
{
store3[i2]= (String) it3.next();
i2++;
// System.out.println(it.next());
}
// ------------------------- Visible Settings start here --------------------//
Object[] hierarchy ={"Click for schools",new Object[] {store[0],new Object[] { "Student Details",store2[0],store2[1] } },new Object[] { store[1],new Object[] { "Student Details",store3[0],store3[1]}}};
DefaultMutableTreeNode root = processHierarchy(hierarchy);
final JTree tree = new JTree(root);
// setSize(275, 300);
jp1.setSize(50,50);
jp1.setBackground(Color.WHITE);
jf1.setExtendedState(Frame.MAXIMIZED_BOTH);
jf1.setLayout(new GridLayout(1,2));
jf1.setVisible(true);
jf1.add(new JScrollPane(tree), BorderLayout.WEST);
jf1.add(jp1);
jp1.setLayout(null);
jl0.setBounds(10,1,500,100);
jp1.add(jl0);
jl1.setBounds(55,90,150,100);
jt1.setBounds(225,130, 155, 25);
jp1.add(jl1);
jp1.add(jt1);
jl2.setBounds(55,160, 150, 100);
jt2.setBounds(225,200, 155, 25);
jp1.add(jl2);
jp1.add(jt2);
jl3.setBounds(55,230,150,100);
jt3.setBounds(225,270, 155, 25);
jp1.add(jl3);
jp1.add(jt3);
jl4.setBounds(55,295, 150, 100);
jt4.setBounds(225,330, 155, 25);
jp1.add(jl4);
jp1.add(jt4);
jb1.setEnabled(false);
jb2.setEnabled(false);
jb1.setBounds(150,430, 100, 50);
jb2.setBounds(350,430, 100, 50);
jp1.add(jb1);
jp1.add(jb2);
//-----------------Visible setting stop here--------------------------//
//------------------- Element actions here------------------------//
jt1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
jb1.setEnabled(true);
jb2.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
jb1.setEnabled(false);
jb2.setEnabled(false);
}
});
//now for the tree
tree.addTreeSelectionListener(new TreeSelectionListener() {
#Override
public void valueChanged(TreeSelectionEvent e) {
jf1.dispose();
//jl0.setText("Displaying information About : "+tree.getLastSelectedPathComponent().toString());
store7[0]= tree.getLastSelectedPathComponent().toString();
System.out.println("in store 7 of 0"+store7[0]);
dbaction db = new dbaction(store7[0]);
}
});
}
//------------------------------------end of action listening-------------------------
private DefaultMutableTreeNode processHierarchy(Object[] hierarchy)
{
DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);DefaultMutableTreeNode child;
for(int i=1; i<hierarchy.length; i++)
{
Object nodeSpecifier = hierarchy[i];
if (nodeSpecifier instanceof Object[]) // Ie node with children
child = processHierarchy((Object[])nodeSpecifier);
else
child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
node.add(child);
}
return(node);
}
private void close()
{
try {
if (resultSet != null)
{
resultSet.close();
}
if (statement != null)
{
//statement.
}
if (connect != null)
{
connect.close();
}
}
catch (Exception e3)
{
e3.printStackTrace();
}
}
}
of course dbaction.java is where I connect to the database and get details.
It is best to create a data model for the tree. How to Use Trees tutorial has good examples. Also go through Understanding the TreeModel for more details.
By the way, don't execute long running tasks such as accessing database on Event Dispatch Thread . Look into SwingWorker for such tasks.
The JTree tutorial to which Max linked has a section covering 'Dynamic updates of a JTree' which contains the necessary snippets on how to update a TreeModel. The basic idea is that you update the model behind the JTree (the TreeModel) and fire the correct events from the TreeModel. The JTree will listen for those events and update itself accordingly.
Next to that, some other advise:
You should only access Swing components on the Event Dispatch Thread (EDT), which is currently not the case in your example. See the Concurrency in Swing tutorial for more information
The moment you adjust your main method to run on the EDT, you should avoid the long running taks (the database access), as it will block the EDT and leave you with an unresponsive UI (as Max already indicated).
You should avoid the null layout and the manual placing of all your components using setBounds. Otherwise simple things like resizing the UI will results in a messed-up layout. Use a LayoutManager instead. The usage of LayoutManagers is also covered in the 'LayoutManager tutorial' on the Oracle site.

Categories