I have created a table called user in mysql. Then I create a simple j frame with having a text field and a button. The button will add the name in the DB after pressing the button. But is showing an error at insertData.InsertData$2.actionPerformed(InsertData.java:86) means there are some issue with prepared statement. I have tried without prepared statement but problem is not solved.
Most important my table having 4 columns called (name, id, Email,Phone)
package insertData;
import java.awt.EventQueue;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import com.mysql.cj.xdevapi.Statement;
import com.sun.jdi.connect.spi.Connection;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class InsertData {
private JFrame frame;
private JTextField textField;
Connection connection;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InsertData window = new InsertData();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public InsertData() {
initialize();
createConnection();
}
/**
* Initialize the contents of the frame.
*/
public void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");//load driver
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/shykat_db","root","root"); //Establish connection
System.out.println("sucess");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(10, 25, 174, 44);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Submit\r\n");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String name=textField.getText();
String drop="insert into user values(?) ";
java.sql.PreparedStatement ps= ((java.sql.Connection) connection).prepareStatement(drop);
System.out.println(ps);
ps.setString(1, name);
ps.executeUpdate();
//ResultSet rs = ps.executeQuery();
//System.out.println(rs);
//java.sql.Statement stm=((java.sql.Connection) connection).createStatement();
//String drop="insert into user values(' "+name+" ')";
//stm.execute(drop);
//stm.close();
//int count=ps.executeUpdate();
//System.out.println(count+"-----Data updated");
ps.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(313, 26, 89, 44);
frame.getContentPane().add(btnNewButton);
}
}
If you want to insert into only some columns of a multi column table, you must declare which columns you want to insert into after the table name
INSERT INTO t(column,list,goes,here)
VALUES(samenumber,ofvalues,asthere,arecolumns)
Your user table has at least 4 columns, you cannot say insert into user values(?) because your database will not be prepared to guess which column the value should go in. Try insert into user(name) values(?)
Related
I made a simple login page with Java Swing in Eclipse and once I run and enter the inputs I am getting an error java.lang.NullPointerException
import java.lang.String;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
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;
public class trail extends JFrame {
Connection connection =null;
private JPanel contentPane;
private JTextField id;
private JPasswordField passwordField;
public static void main(String[] args) {
String jdbcURL = "jdbc:postgresql://localhost:5432/postgres";
String username = "postgres";
String password = ".......";
try {
Connection connection = DriverManager.getConnection(jdbcURL, username, password);
System.out.print("Connected");
connection.close();
}
catch(SQLException e) {
System.out.println("Error in connection");
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
trail frame = new trail();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public trail() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 519, 550);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("username");
lblNewLabel.setBounds(94, 114, 45, 13);
contentPane.add(lblNewLabel);
id = new JTextField();
id.setBounds(246, 111, 96, 19);
contentPane.add(id);
id.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("password");
lblNewLabel_1.setBounds(94, 178, 45, 13);
contentPane.add(lblNewLabel_1);
passwordField = new JPasswordField();
passwordField.setBounds(246, 175, 96, 19);
contentPane.add(passwordField);
JButton btnlogin = new JButton("login");
btnlogin.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
try {
String query = "select * from users where username = ? and password = ?";
PreparedStatement pst=connection.prepareStatement(query);
pst.setString(1, id.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()) {
count = count + 1;
if(count == 1)
{
JOptionPane.showMessageDialog(null, "Password and username is correct");
}
else if(count>1)
{
JOptionPane.showMessageDialog(null, "redundancy detected");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect credentials");
}
}
rs.close();
pst.close();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, e1);
}
}
});
btnlogin.setBounds(179, 259, 85, 21);
contentPane.add(btnlogin);
}
}
You have declared Connection connection =null; later on in the try block you are using like
Connection connection = DriverManager.getConnection(jdbcURL, username, password) which is altogether different Connection object. you should be using something like .
this.connection=DriverManager.getConnection(jdbcURL, username, password)
Also you can move your code in a different method like
public void initialize() {
String jdbcURL = "jdbc:postgresql://localhost:5432/your_db";
String username = "postgres";
String password = "password";
try {
this.connection = DriverManager.getConnection(jdbcURL, username, password);
System.out.print("Connected");
connection.close();
}
catch(SQLException e) {
System.out.println("Error in connection");
e.printStackTrace();
}
}
And call inside the constructor like
public trail() {
initialize();
....
}
I have a text box that allows users to put in select type queries with the idea that when they click a button the result of the select statement will be shown in a JTable. I don't get any errors but also nothing is shown in the textPane when my button is pressed. The I have is below:
public class Console {
String myquery="";
private JFrame frame;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Console window = new Console();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Console() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 950, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textAreaQuery = new JTextArea();
JTable table_ResQues = new JTable();
JButton btnNewButton = new JButton("Execute");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String connectDB = "jdbc:ucanaccess:///Users/sebastianzeki/Documents/PhysJava/Physiology.mdb;";
System.out.println("Connection To Database Made");
Connection conn = null;
try {
conn = DriverManager.getConnection(connectDB);
} catch (SQLException e1) {
e1.printStackTrace();
}
Statement st = null;
try {
st = conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
myquery=textAreaQuery.getText();
String stg2 = "Select "+myquery;
ResultSet rs = null;
try {
rs = st.executeQuery(stg2);
table_ResQues.setModel(getDataFromDatabase);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
and the code to build the model:
public TableModel getDataFromDatabase()
{
DefaultTableModel model = new DefaultTableModel(5, 5);
model.setValueAt("Hard", 0, 0);
model.setValueAt("Coded", 1, 1);
model.setValueAt("Data", 2, 2);
return model;
}
}
Ive removed the local variable
No, you removed the instance variable. Did you actually try this with your real code or just edit the question?
I have no idea how to provide a testable database for this question
I already suggested you create a method to simplify the logic. Somethng like:
public TableModel getDataFromDatabase()
{
DefaultTableModel model = new DefaultTableModel(5, 5);
model.setValueAt("Hard", 0, 0);
model.setValueAt("Coded", 1, 1);
model.setValueAt("Data", 2, 2);
return model;
}
Then in your ActionListener you simple do something like:
table_ResQues.setModel( getDataFromDataBase() );
Once you get this basic logic working you move the SQL logic into the getDataFromDatabase() method.
So now you create your SSCCE showing how you actually create the frame and add the components to the frame. The code should be compilable and executable.
Edit:
You have been told to display a table is a scrollpane. It is no extra effort to do this. Instead of using:
panel.add(table);
you use:
panel.add( new JScrollPane( table ) );
I would also suggest that to test your layout you can use code like the following to display a dummy table:
//JTable table_ResQues = new JTable();
JTable table_ResQues = new JTable(5,5);
Then when you use the setModel() method, only the data is affected, not the layout of the table.
I cant help but feel this is a fireTableDataChanged problem though.
I doubt it. That method is invoked by the TableModel when you change the data in the model. It is not used in this case because you are using the setModel(...) method. This will cause the table to repaint() itself automatically.
Here is my solution to your problem. I have retained your variable names though not all of them followed Java conventions. I think all you wanted was that the user would type SQL query in JTextArea and see the result of the query in a JTable.
import java.awt.BorderLayout;
import java.awt.EventQueue;
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.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.AbstractTableModel;
public class Console {
private JFrame frame;
private JTextArea textAreaQuery;
private JTable table_ResQues;
private JButton btnNewButton;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Console window = new Console();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Console() {
initialize();
}
private void initialize() {
frame = new JFrame("SQL Query");
frame.setBounds(100, 100, 950, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textAreaQuery = new JTextArea();
btnNewButton = new JButton("Execute");
table_ResQues = new JTable();
JPanel queryPanel=new JPanel(new BorderLayout()); // holds JTextArea and JButton
queryPanel.add(new JScrollPane(textAreaQuery), BorderLayout.CENTER);
JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
btnPanel.add(btnNewButton);
queryPanel.add(btnPanel, BorderLayout.SOUTH);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, queryPanel,
new JScrollPane(table_ResQues));
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(150);
frame.setContentPane(splitPane);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/*try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e2) {
e2.printStackTrace();
}*/
String connectDB = "jdbc:ucanaccess:///Users/sebastianzeki/Documents/PhysJava/Physiology.mdb;";
Connection conn = null;
Statement st = null;
try {
conn = DriverManager.getConnection(connectDB);
//conn = DriverManager.getConnection("jdbc:mysql://localhost/cwcx", "root", "admin");// MySQL connection
st = conn.createStatement();
System.out.println("Connection To Database Made");
} catch (SQLException e1) {
e1.printStackTrace();
}
String myquery = textAreaQuery.getText();
if(myquery.endsWith(";")){
myquery=myquery.substring(0, myquery.length()-1);
}
ResultSet rs = null;
try {
rs = st.executeQuery(myquery);
// extract column information
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
List<String> columnData = new ArrayList<String>(columnCount);
for (int i = 1; i <= columnCount; i++) {
columnData.add(rsmd.getColumnName(i));
}
// sql result data
List<List<Object>> rowData = new ArrayList<List<Object>>();
while (rs.next()) {
List<Object> row = new ArrayList<Object>(columnCount);
for (int i = 0; i < columnCount; i++) {
row.add(rs.getObject(i + 1));
}
rowData.add(row);
}
table_ResQues.setModel(new ListTableModel(rowData, columnData));
} catch (SQLException e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
});
}
// this table model is created from two dimensional List rowData and single dimensional List columnData
private static class ListTableModel extends AbstractTableModel{
private static final long serialVersionUID = 1L;
private List<List<Object>> rowData;
private List<String> columnData;
public ListTableModel(List<List<Object>> rowData, List<String> columnData) {
this.rowData = rowData;
this.columnData = columnData;
}
#Override
public int getRowCount() {
return rowData.size();
}
#Override
public int getColumnCount() {
return columnData.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return rowData.get(rowIndex).get(columnIndex);
}
#Override
public String getColumnName(int column) {
return columnData.get(column);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Object obj=rowData.get(0).get(columnIndex);
return obj.getClass();
}
}
}
On my system, I have tested it with MySQL database. But I have commented out that part. You may try this on your system without any modification. Please do tell me whether you wanted to achieve this solution or not.
Here i am trying to retrieve a image stored in BLOB format and storing it in another table in the same BLOB format only! And one more issue is this that i have a JFrame named WelcomeStaffs from which i have to access the JTextField named subject_txt and staff_txt values and store it in the database.. But those are only blank! Not getting printed in the output, while i print it!
Here is the code of the FaceRecognizer class..
import static cern.jet.math.Bessel.i1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import facedetection.*;
import com.googlecode.javacv.*;
import com.googlecode.javacv.cpp.*;
import com.googlecode.javacpp.Loader;
import com.mysql.jdbc.Connection;
import java.sql.Blob;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FaceRecognizer extends JFrame
{
// GUI components
private FaceRecogPanel facePanel;
private JButton recogBut;
private JTextField nameField; // where the name (and distance info) appears
private JButton done;
private JButton exit;
public FaceRecognizer()
{
super("Face Recognizer");
FaceRecognizer fac;
Container c = getContentPane();
c.setLayout( new BorderLayout() );
// Preload the opencv_objdetect module to work around a known bug.
Loader.load(opencv_objdetect.class);
facePanel = new FaceRecogPanel(this); // the sequence of pictures appear here
c.add( facePanel, BorderLayout.CENTER);
// button for recognizing a highlighted face
done = new JButton("Done");
recogBut = new JButton("Recognize Face");
recogBut.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e)
{ nameField.setText("");
recogBut.setEnabled(false);
facePanel.setRecog();
}
});
done.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
WelcomeStaffs wc = new WelcomeStaffs();
Connection con = null;
try{
String url = "jdbc:mysql://localhost:3306/facedetection";
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Conncection Success");
con = (Connection) DriverManager.getConnection(url, "root", "2204");
System.out.println("Database Connected");
}
catch(Exception ex)
{
System.out.println("Exception = "+ex);
}
String nm = nameField.getText().toUpperCase();
String name ="",course="";
System.out.println("Hello im till here!!");
String subject = wc.subject_txt.getText();
String staff = wc.staff_txt.getText();
String day = wc.day_txt.getText();
String date = wc.date_txt.getText();
String time = wc.time_txt.getText();
int roll_no = 0;
System.out.println(subject+staff);
String sql = "SELECT roll_no,name,course,photo FROM students WHERE name=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,nm);
ResultSet rs = ps.executeQuery();
while(rs.next()) //retrieving values from database and storing it!
{
roll_no = rs.getInt("roll_no");
name = rs.getString("name");
course = rs.getString("course");
byte[]imagedata = rs.getBytes("photo");
image = Toolkit.getDefaultToolkit().createImage(imagedata);
format = new ImageIcon(image);
System.out.println("Retrieved Data!!!!!!!");
}
} catch (SQLException ex) {
Logger.getLogger(FaceRecognizer.class.getName()).log(Level.SEVERE, null, ex);
}
try{
if(roll_no == 0 || name.equals("") || course.equals(""))
{
System.out.println("EMPTY");
}
else
{
sql = "INSERT INTO attendance(roll_no, name, course, subject, staff, day, time, date, photo) VALUES(?,?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql);
ps1.setInt(1,roll_no);
ps1.setString(2,name);
ps1.setString(3,course);
ps1.setString(4,subject);
ps1.setString(5,staff);
ps1.setString(6,day);
ps1.setString(7,time);
ps1.setString(8,date);
ps1.setBlob(9, (Blob) format);
int i1 = ps1.executeUpdate();
JOptionPane.showMessageDialog(null,i1+" Data Inserted");
}
}
catch(Exception ec)
{
System.out.println(""+ec);
}
}
});
nameField = new JTextField(20); // for the name of the recognized face
nameField.setEditable(false);
JPanel p = new JPanel();
p.add(recogBut);
p.add( new JLabel("Name: "));
p.add( nameField);
p.add(done);
c.add(p, BorderLayout.SOUTH);
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ facePanel.closeDown(); // stop snapping pics
/*Attendance_Chart ac = new Attendance_Chart();
ac.setVisible(true);*/
System.exit(0);
}
});
pack();
setResizable(false);
setVisible(true);
} // end of FaceRecognizer()
public void setRecogName(final String faceName, final String dist)
// update face name and its distance in the nameField; called from panel
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{ nameField.setText( faceName);
recogBut.setEnabled(true);
}
});
} // end of setRecogName()
// -------------------------------------------------------
public static void main( String args[] )
{
new FaceRecognizer();
}
public ImageIcon format = null;
public Image image = null;
public Blob blob = null;
}
// end of FaceRecognizer class
Here is the output i get!
Conncection Success for Staffs
detection/recognition duration: 9ms
Database Connected for Staffs
Table Created
Conncection Success
Database Connected
Hello im till here!!
Retrieved Data!!!!!!!
java.lang.ClassCastException: javax.swing.ImageIcon cannot be cast to `java.sql.Blob`
Please help!
Thank you!
I am using a JTable to display data from my database. What I want to happen is that when a row is clicked it opens another window.
My Code
Connection to the database
public class JFrametest extends javax.swing.JFrame {
private static Connection connection;
private static Statement stmt;
static {
// standard code to open a connection and statement to Java Derby database
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("EmailsDB").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "student", "student");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
out.println(cnfe);
} catch (SQLException sqle) {
out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
Displaying Data from the database
try {
String query = "select * from messages";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e) {
e.printStackTrace();
}
As anyone got any ideas on what i can do? is this possible?
You could use a mouseClicked Action Listener to do this.
You can use MouseListener for that, here is simple example:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestFrame extends JFrame {
public static void main(String... s) {
new TestFrame();
}
private JTable t;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
DefaultTableModel model = new DefaultTableModel(0,2);
for(int i=0;i<10;i++){
model.addRow(new Object[]{i,"other info "+i});
}
model.setColumnIdentifiers(new Object[]{"id","info"});
t = new JTable(model);
t.addMouseListener(getListener());
add(new JScrollPane(t));
}
protected void showDialog(int rowAtPoint) {
Object valueAt = t.getValueAt(rowAtPoint, 0);
// other operations
JDialog d = new JDialog();
d.setTitle("id="+valueAt);
d.setModal(true);
d.setAlwaysOnTop(true);
d.setLocationRelativeTo(null);
d.pack();
d.setVisible(true);
}
private MouseListener getListener() {
return new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getClickCount() >= 1){
int rowAtPoint = t.rowAtPoint(e.getPoint());
if(rowAtPoint != -1)
showDialog(rowAtPoint);
}
}
};
}
}
Trying to pass an SQL query to a Jtable as the Frame/Jtable_1 loads.
looking into the forums and on the net I seem to end at WindowOpened event or some abstract example, which i have commented out.
I am new to Java and thought it may be Jtable setFocus event or on onload event etc but now struggling as i pick up knowledge, although a button Actionperformed event works a treat.
Any help would be appreciated.
Eclipse IDE Luna 4.4.1/ SQLite / Windows8.1
enter code here
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;
import java.awt.event.ActionListener;
public class update extends JFrame {
private JPanel contentPane;
//private String x = Hardware.rowid;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
update frame = new update();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowOpened(WindowEvent e){
System.out.println("hello");
//Connection connection=null;
//connection=sqliteConnection.dbConnector(); //set new connection to sql
//String query="select id, Firstname, Surname, username, admin from users where id = "+ Hardware.rowid ; //set sql query statement to variable query
//PreparedStatement pst;
//try {
//pst=connection.prepareStatement(query);
// ResultSet rs=pst.executeQuery(); //pass to rs resultset and execute
//table_1.setModel(DbUtils.resultSetToTableModel(rs)); //pass data to table
//} catch (SQLException e1) {
// TODO Auto-generated catch block
// e1.printStackTrace();
//}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection=null;
// WindowListener wl = new WindowListener(){
// public void windowOpened(WindowEvent e)
// {
// try
// {
// System.out.println (Hardware.rowid);
// }
// catch (FileNotFoundException ex) {
// System.out.println ("didnt work");
// }
// }
// public void windowClosing(WindowEvent e) {}
// public void windowClosed(WindowEvent e) {}
// public void windowIconified(WindowEvent e) {}
// public void windowDeiconified(WindowEvent e) {}
// public void windowActivated(WindowEvent e) {}
// public void windowDeactivated(WindowEvent e) {}
//};
//super.getFrame().addWindowListener(wl);
//}
private JTable table;
//private static JTable table_1;
private JTable table_1;
/**
* Create the frame.
*/
public update() {
connection=sqliteConnection.dbConnector(); //set new connection to sql
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btn_update = new JButton("Update Database");
btn_update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query="select id, Firstname, Surname, username, admin from users where id = "+ Hardware.rowid ; //set sql query statement to variable query
PreparedStatement pst=connection.prepareStatement(query); //passs data to pst
ResultSet rs=pst.executeQuery(); //pass to rs resultset and execute
table_1.setModel(DbUtils.resultSetToTableModel(rs)); //pass data to table
System.out.println (Hardware.rowid);
} catch (Exception e) {
e.printStackTrace();
}
}
});
btn_update.setBounds(270, 219, 154, 31);
contentPane.add(btn_update);
JLabel lbl_update = new JLabel("Selection HISTORY");
lbl_update.setBounds(142, 11, 160, 14);
contentPane.add(lbl_update);
table_1 = new JTable();
table_1.setBounds(20, 36, 404, 175);
contentPane.add(table_1);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(246, 102, 2, 2);
contentPane.add(scrollPane);
}
}
Thanks in advance.