how to retrieve data from db automatic of given id? - java

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();

Related

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) {
......... }

embed MS Access database with runnable jar

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

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.

DB creation and deletion in mysql

I use the following code to create new Database. If the given Database name is same as existing Database name means the existing Database need to be deleted else the new data base need to be created with the given name. I have error in creating new database.
package db1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Main implements ActionListener
{
JTextField txt;
JButton create;
JFrame frame;
JPanel panel;
JOptionPane jop;
//Font font = UIManager.getFont("txt.font");
public Main()
{
frame=new JFrame();
panel=new JPanel();
txt=new JTextField(10);
create=new JButton("create");
create.setBounds(20, 200, 50, 40);
panel.add(txt);
panel.add(create);
create.addActionListener(this);
frame.add(panel);
// n.getContentPane().add(new textf());
frame.setSize(440,310);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay1","root","root");
try{
Statement st = con.createStatement();
String database=txt.getText();
st.executeUpdate("DROP DATABASE IF EXISTS "+database);
JOptionPane.showMessageDialog(frame,"EXISTING DATABASE DELETED");
st.executeUpdate("CREATE DATABASE "+database);
JOptionPane.showMessageDialog(frame,"DATABASE CREATED");
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception ea){
ea.printStackTrace();
}
}
public static void main(String[] args)
{
new Main();
}
}
Try this as your inner try block, hope this will help.
try
{
String database=txt.getText();
String query = "if exists(select * from sys.databases where (name = ?))"
+ "drop database " + database
+ "create database " + database;
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, database);
statement.executeUpdate();
JOptionPane.showMessageDialog(frame,"EXISTING DATABASE DELETED");
JOptionPane.showMessageDialog(frame,"DATABASE CREATED");
}
Regards

Categories