ResultSet disappears after updating rows - java

The only thing remotely similar to my issue that I could find was this, however his problem seemed to be from a user error.
Reset cursor position after ResultSet updateRow
My problem is the following: After updating a row I am not able to access any other rows in my ResultSet. The update itself works fine, but if I want to continue I have to restart the application.
Here's the code:
package database;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Gui extends MyDB {
JFrame f;
JLabel FName;
JLabel LName;
JLabel Age;
JTextField t;
JTextField t2;
JTextField t3;
JButton next = new JButton("next");
JButton update = new JButton("Update");
public Gui() {
frame();
start();
btnAction();
}
public void frame() {
f = new JFrame();
f.setVisible(true);
f.setSize(680, 480);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FName = new JLabel("Name");
LName = new JLabel("Anrede");
Age = new JLabel("age");
t = new JTextField(10);
t2 = new JTextField(10);
t3 = new JTextField(10);
JPanel p = new JPanel();
p.add(FName);
p.add(t);
p.add(LName);
p.add(t2);
p.add(Age);
p.add(t3);
p.add(b1);
p.add(update);
public void btnAction() {
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String FName = t.getText();
String LName = t2.getText();
String Age = t3.getText();
try {
System.out.println(rs.getRow());
rs.updateString("FName", FName);
rs.updateString("LName", LName);
rs.updateString("Age", Age);
rs.updateRow();
//System.out.println(rs.getString("FName"));
System.out.println(rs.getRow());
JOptionPane.showMessageDialog(null, "Record updated ");
} catch (Exception ex) {
System.out.println("no");
}
}
});
}
public void start() {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
}
Also:
package database;
import java.sql.*;
public class MyDB {
Connection con;
Statement st;
ResultSet rs;
public MyDB() {
connect();
}
public void connect() {
try {
String db = "jdbc:ucanaccess://Datenbank1.accdb";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select * from Tabelle1";
rs = st.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace(System.out);
}
}
public static void main(String[] args) {
new Gui();
}
}
Output of System.out.println(rs.getRow()); is '0'.
If I want to click on the 'next' button after updating, the message "no next records" is displayed.
I have tried using rs.first(), rs.beforeFirst() and rs.isBeforeFirst(), none of which have worked.
If it helps, I am following this tutorial, which does not run into the same problem:
https://www.youtube.com/watch?v=NPV2o6YjP10

Related

Buttons are not working. Entering Data through TextFields

I want to enter data through textfields and save them. But buttons are not working. There are no errors while I'm compiling and not even in database connection. I guess there is a logical error.
public class Database {
private static JPanel panel;
private static JLabel sname;
private static JLabel saddress;
private static JTextField t;
private static JTextField t1;
private static JButton Delete = new JButton("Delete");
private static JButton update = new JButton("Update");
private static JButton save = new JButton("Save");
private static Container c;
private static Connection con;
private static Statement st;
private static ResultSet rs;
Database() {
connect();
}
public void connect(){
try{
System.out.println("Entered");
System.out.println("Database connection started...");
con=DriverManager.getConnection("jdbc:ucanaccess://D:\\test.mdb");
System.out.println("Hello satarted");
st = con.createStatement();
System.out.println("Connection ok.");
while(rs.next())
{
System.out.println(rs.getString("Student Name"));
System.out.println(rs.getString("Student Address"));
System.out.println();
}
catch (SQLException e){
System.err.println("Exception: " + e.getMessage());
}
}
public static void main(String[] args) {
Database gui = new Database();
JFrame f = new JFrame();
f.setTitle("School Management System");
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sname = new JLabel("Student Name");
t = new JTextField(10);
saddress = new JLabel("Student Address");
t1 = new JTextField(10);
panel = new JPanel();
panel.add(sname);
panel.add(t);
panel.add(saddress);
panel.add(t1);
// panel.add(insert);
panel.add(Delete);
panel.add(update);
panel.add(save);
f.add(panel);
try {
rs.next();
t.setText(rs.getString("Student Name"));
t1.setText(rs.getString("Student Address"));
} catch (Exception ex) {
}
}
public void btnAction() {
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = t.getText();
String address = t1.getText();
try {
rs.moveToInsertRow();
rs.updateString("Student Name", name);
rs.updateString("Student Address", address);
rs.insertRow();
rs.close();
} catch (Exception ex) {
}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String sname = t.getText();
String saddress = t1.getText();
try {
rs.updateString("Student name", sname);
rs.updateString("Student address", saddress);
rs.updateRow();
JOptionPane.showMessageDialog(null, "Record Updated!");
} catch (Exception e) {
}
}
});
}
}
when i removed static from each of these variables. I got so many errors
Yes, any time you see a class full of static variables you know the class is designed incorrectly.
Start with the working example from the Swing tutorial on How to Use Text Field. Download the TextDemo code and understand how it works and then make the changes for your logic.
Note how the class extends a JPanel where all the variables and components are defined and there is no need for any static variable. Your code should look something like this.
Once you have a better designed class you can then start to debug your code to figure out why the SQL isn't working.

JDBC connection for .accdb access database in java

Every thing is right in the given program but connection to database is not established.
What could be the possible reason?Is it driver related problem. I want to do this without DSN.
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class FormAccess1 extends Frame implements ActionListener {
private static ResultSet rs;
Panel p1;
TextField t1, t2;
Button next;
public FormAccess1() {
super("Applicant Detail");
setLayout(new GridLayout(5, 1));
p1 = new Panel();
t1 = new TextField(10);
t2 = new TextField(10);
add(p1);
next = new Button("Next");
p1.add(new Label("book-id"));
p1.add(t1);
p1.add(new Label("book-title"));
p1.add(t2);
p1.add(next);
next.addActionListener(this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == next) {
try {
rs.next();
} catch (Exception em) {
}
showRecord(rs);
}
}
public void showRecord(ResultSet rs) {
try {
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
} catch (Exception ex) {
}
}
public static void main(String arg[]) {
FormAccess1 app = new FormAccess1();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.accdb)};DBQ=MyDatabase.accdb;DriverID=01";
Connection con = DriverManager.getConnection(database, "", "");
Statement state = con.createStatement();
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
rs.next();
app.showRecord(rs);
} catch (Exception ey) {
}
}
}
Verify you have de correct access drivers in the machine (Access 2013 redistributables). It could be x86 or x64. Jre/Jdk should be in concordance: x86 or x64

Making authorization JFrame with MS Access base

I'm trying to make a authorization JFrame to MS Access DB, but query does'nt seems to wirk properly. The idea is to intup login and password, and if one of them isn't correct, get a message. My code always sends me to the exception. Here is my code, maybe someone can help me.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class First {
JFrame frame;
JPanel txt, but;
JButton log, ext;
JTextField login;
JLabel l, p;
JPasswordField pass;
PreparedStatement prepst;
ResultSet res;
public First() {
frame = new JFrame("Authorization");
txt = new JPanel();
but = new JPanel();
log = new JButton("Login");
ext = new JButton("Quit");
login = new JTextField(10);
l = new JLabel("Login:");
p = new JLabel("Password:");
pass = new JPasswordField(10);
frame.setSize(400,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt.add(l);
txt.add(login);
txt.add(p);
txt.add(pass);
frame.add(txt,BorderLayout.NORTH);
but.add(log);
but.add(ext);
frame.add(but,BorderLayout.SOUTH);
log.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String PathToDataBase = "D:/workspace2/MicrosoftAccessConnection/db";
String DataBase = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
DataBase += PathToDataBase.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection(DataBase,"","");
prepst = con.prepareStatement("SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?");
String lll = login.getText();
String ppp = pass.getText();
prepst.setString(1,lll);
prepst.setString(2, ppp);
res = prepst.executeQuery();
if((test(con,lll,ppp)) == true) {
while(res.next()) {
if((lll.equals(res.getString("LOGIN"))) && (ppp.equals(res.getString("PASSWORD")))) {
lol();
} else {
JOptionPane.showMessageDialog(null, "Wrong data");
}
}
}
res.close();
prepst.close();
con.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error with connection");
}
}
});
ext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
frame.dispose();
}
});
frame.setVisible(true);
}
public void lol() {
JFrame f = new JFrame("SUCCESS");
f.setSize(200,200);
frame.dispose();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
boolean test(Connection con, String login, String pass) throws SQLException {
int rez = 0;
PreparedStatement st = con.prepareStatement("SELECT COUNT(*) FROM USERS WHERE LOGIN=? AND PASSWORD=?");
st.setString(1, login);
st.setString(2, pass);
ResultSet res = st.executeQuery();
while (res.next()) {
rez = res.getInt(1);
}
st.close();
return rez == 1;
}
public static void main(String[] args) {
new First();
}
}
You're missing a PreparedStatement placeholder character from your SQL, replace
SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?
with
SELECT * FROM USERS WHERE LOGIN=? AND PASSWORD=?
^
If you're getting an Exception, its always best to display the exception content. You could add this to the exception block:
e.printStackTrace();

how to show output from console to JTextArea

I am beginner in Java Programming. How can i show my output from console to JTextArea. Here my code only show the output console. Anyone could tell or show me how can i do it.Thanks.
import java.sql.*;
public class Route
{
public void routeList()
{
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "YarraTram";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "abc123";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
PreparedStatement statement = conn.prepareStatement("Select rid,route from route");
ResultSet result = statement.executeQuery();
while(result.next())
{
System.out.println(result.getString(1)+" "+result.getString(2));
}
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
here is another file
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI
{
public void createAndShowGUI()
{
JButton button2 = new JButton("Route");
//create a frame
JFrame frame = new JFrame("Yarra Tram Route Finder");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(button2);
button2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
showNewFrame();
Route route = new Route();
route.routeList();
}
public void showNewFrame()
{
JFrame frame = new JFrame("Yarra Tram Route Finder (Route)" );
JTextArea textArea = new JTextArea();
frame.add(textArea);
frame.setSize(500,120);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
textArea.setEditable( false );
}
});
frame.pack();
frame.setSize(350,100);
frame.setVisible(true);
}
}
Modified changes in your existing code. Check this
public class GUI extends JFrame {
JButton button2;
JTextArea textArea;
public GUI() {
super("Yarra Tram Route Finder");
}
public void routeList() {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "YarraTram";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "abc123";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement statement = conn.prepareStatement("Select rid,route from route");
ResultSet result = statement.executeQuery();
StringBuilder strBuilder = new StringBuilder();
while (result.next()) {
strBuilder.append(result.getString(1)).append(" ").append(result.getString(2));
strBuilder.append("\n");
}
textArea.setText(strBuilder.toString());
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void createAndShowGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
button2 = new JButton("Route");
textArea = new JTextArea(20, 20);
add(textArea);
add(button2);
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
routeList();
}
});
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI gui = new GUI();
gui.createAndShowGUI();
}
});
}
}

JTable getSelectedRow does not return the selected row index

I try to get data in the row that is selected but getSelectedRow() doesn't work. Actually, I used that method in the other class, but it works in there. When I try to print the row index; the prompt shows -1; as not selected.
I tried most of solutions that are on the internet but they didn't solve my solutions.
public Canteen() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout( null );
this.setSize( new Dimension(400, 300) );
this.setTitle( "CANTEEN" );
jScrollPane1.setBounds(new Rectangle(0, 0, 230, 235));
jButton1.setText("REFRESH");
jButton1.setBounds(new Rectangle(0, 235, 100, 20));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jButton2.setText("CLOSE");
jButton2.setBounds(new Rectangle(120, 235, 110, 20));
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton2_actionPerformed(e);
}
});
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
jTable1 = new JTable (model);
String header [] = {"CUSTOMER", "PRODUCT", "QUANTITY","ORDER NO"};
for (int i = 0; i < 4; i++){
model.addColumn(header[i]);
}
//refresh every 1 minute
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
public void run(){
model.setRowCount(0);
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,username, password);
statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT USER_NAME, QUANTITY, PRD_NAME, ORDER_NUMBER FROM ORDERS ORDER BY ORDER_NUMBER DESC");
int count = rs.getRow();
String user [] = new String [count];
int i = 0;
while (rs.next()){
String name = rs.getString(1);
String prdName = rs.getString(3);
int number = rs.getInt(2);
int orderNumber = rs.getInt(4);
model.insertRow(i,new Object []{name,prdName,number, orderNumber});
}
conn.close();
}
catch (ClassNotFoundException s) {
System.out.println("Couldn't find the database driver");
System.out.println(s);
}
catch (SQLException s) {
System.out.println("Couldn't connect to the database\n" +s);
}
}
},0, 60000);
}
private void jButton1_actionPerformed(ActionEvent e) {
//set from row 0 for refresh
model.setRowCount(0);
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,username, password);
statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT USER_NAME, QUANTITY, PRD_NAME FROM ORDERS ORDER BY ORDER_NUMBER DESC");
int count = rs.getRow();
String user [] = new String [count];
int i = 0;
while (rs.next()){
String name = rs.getString(1);
String prdName = rs.getString(3);
int number = rs.getInt(2);
model.insertRow(i,new Object []{name,prdName,number});
}
conn.close();
}
catch (ClassNotFoundException s) {
System.out.println("Couldn't find the database driver");
System.out.println(s);
}
catch (SQLException s) {
System.out.println("Couldn't connect to the database\n" +s);
}
}
private void jButton2_actionPerformed(ActionEvent e) {
System.out.println(jTable1.getSelectedRow());
}
}
Look to your code
private void jbInit() throws Exception {
...
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
jTable1 = new JTable (model);
...
You add jTable1 to the JScrollPane at first and only then you create jTable1. It's incorrect way. jTable1 variable doen't linked now with table you place at the form. I think it's cause of your problem.
Move creation of the jTable1 before adding in into JScrollPane.
...
jTable1 = new JTable (model);
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
...
As your other example shows, getSelectedRow() does work, so you're going to have to debug your code. Comparison with the sscce below may suggest way forward. Both the ActionListener and the ListSelectionListener show the selected row.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
/**
* #see http://stackoverflow.com/q/12301923/230513
*/
public class TableSelection extends JPanel {
private static final String SHOW = "Show";
private DefaultTableModel model = new DefaultTableModel();
private JTable table = new JTable(model);
private JButton button = new JButton(new AbstractAction(SHOW) {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(table.getSelectedRow());
}
});
public TableSelection() {
model.addColumn("Column");
for (int i = 0; i < 16; i++) {
model.addRow(new Object[]{i});
}
table.setPreferredScrollableViewportSize(new Dimension(160, 100));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
button.setText(SHOW + " " + table.getSelectedRow());
}
}
});
this.add(new JScrollPane(table));
table.setRowSelectionInterval(3, 3);
}
private void display() {
JFrame f = new JFrame("TableSelection");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this, BorderLayout.CENTER);
f.add(button, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new TableSelection().display();
}
});
}
}

Categories