How to Retrieve auto incremented ID value to a JLabel - java

I have a mysql Database which as Book Id (auto incrementing when I add data) and other rows. I have wrote a code to get the incremented value to a jLabel and it works fine too but still there is a one more little problem. assume I have entered 5 book details. so when I press the Save button (to save the details to database) it saves successfully and jLabel shows the incremented value as 6 (so it works fine).
Now the problem is, every time I closed my application and restart it, the jLabel shows the value as 1. Then when I save another book detail it skip to number 7 (which is the correct auto incremented ID). But Why is it showing the ID as 1, when I restart the application? It should read 7 even after I restart it. Here is the code sample. I have even call it in the class Constructor. But it doesn't seem to update. :(
private void autoGenerateId() {
if (true) {
try {
ResultSet result = new JDBC().getData("SELECT * FROM newbookstock");
if (!result.next()) {
jLabel5.setText("1");
} else {
ResultSet result2 = new JDBC().getData("SELECT LAST_INSERT_ID() AS bookid FROM newbookstock");
if (result2.next()) {
int id = result2.getInt("bookid") + 1;
String ss = String.valueOf(id);
jLabel5.setText(ss);
} else {
System.out.println("OOOOO");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Set focus to Jtext1");
}
}

let's digest your code.
ResultSet result = new JDBC().getData("SELECT * FROM newbookstock");
if (!result.next()) {
This if condition will evaluate to false if the table is empty. So this is not where you are setting the label as 1
} else {
ResultSet result2 = new JDBC().getData("SELECT LAST_INSERT_ID() AS bookid FROM newbookstock");
Ah, but what do you get here when you first start the program? 0. Why because you have not inserted any values into the table with your current connection.
What you ought to do is
SELECT COUNT(*) FROM newbookstock
where you do
SELECT * FROM newbookstoc
or perhaps you might want MAX(id) instead of count(*) but select * is definitelly not what you should be using.
and use that value as your initial value. In other news, you have
new JDBC().getData(...)
in two locations. You shouldn't open multiple connections like this. Open the connection once and reuse it.
update: your snippet to set the initial value might look like:
JDBC conn = new JDBC();
ResultSet result = jdbc.getData("SELECT COUNT(*) as C FROM newbookstock");
jLabel5.setText(result2.getString("C"));

Related

How to pass Each database table row into relavent jLabels in Java mysql

i am create a simple rating system. i have only 3 question the database table. i attached screen shot image below.
those question are
a
b
c
what i need is i have put 3 jLabels in JFrame i need to fetch the from database table and pass in to relavent
Jlables i attached the screen shot below.
but result only displayed c only means last row data only displayed. i need to display question 1 - a,
question 2 - b,question 3 - c . how to do it what i tried so far i attached below.
public void question()
{
String query = "select * from rate";
Statement stat =null;
ResultSet rs;
try {
stat = con.createStatement();
rs = stat.executeQuery(query);
while(rs.next())
{
lblq1.setText(rs.getString(2));
lblq2.setText(rs.getString(2));
lblq3.setText(rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Try changing this:
while(rs.next())
{
lblq1.setText(rs.getString(2));
lblq2.setText(rs.getString(2));
lblq3.setText(rs.getString(2));
}
into something like this:
int id = 1;
while(rs.next())
{
if ( id == 1 ) lblq1.setText(rs.getString(2));
if ( id == 2 ) lblq2.setText(rs.getString(2));
if ( id == 3 ) lblq3.setText(rs.getString(2));
id += 1;
}
In your current code, you set the text for all three feelds for every value, and you end up with all of them containing the last value.
You need to check which value you want to set in which field.
There are better (more efficient) ways to write this code (switch / if else if ) but for an example, this should be sufficient.

How to load exact number of rows to jTable from MySQL and paginate the remaining?

I am trying to load data from MySQL into my Application, where I have a jTable. I want to load only 100 rows using a query, and I can do that successfully as of now. furthermore, I want to paginate that data, in such a way that if I have the next button, and I click on that, the table should be updated with 100 more records and so on.
This method loads the data into the table:
public void showTable(){
try{
how.res = how.stat.executeQuery("select * from students order by name ASC limit 100");
while(how.res.next()){
String id = how.res.getString(1);
String name = how.res.getString(2);
String contact = how.res.getString(3);
Object[] content = {id,name,contact};
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(content);
}
}catch (Exception e){
}
}
I call this method on form Initialization, and now I only get 100 rows into the table, what should I write for the next button to load next 100 rows and update the table?
What I tried:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
numClick+=100;
how.res = how.stat.executeQuery("select * from students offset"+numClick+"");
while(how.res.next()){
String id = how.res.getString(1);
String name = how.res.getString(2);
String contact = how.res.getString(3);
Object[] content = {id,name,contact};
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(content);
}
}catch (Exception e){
}
}
But this does not give me any result.
Here is the Connection:
public class JoinConnection {
public Connection con;
public Statement stat;
public ResultSet res;
public JoinConnection(){
systemConnection();
}
public void systemConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
con =(com.mysql.jdbc.Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","");
stat = (Statement) con.createStatement();
}catch(ClassNotFoundException | SQLException e){System.out.println(e);}
}
}
I am using NetBeans with MySQL. if the question is not clear, please tell me for clarification.
EDIT: Thanks to #George Z. We solved the problem by changing the button method into something like below. I am editing the question because I can not write the answer in comments:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
numClick+=100;
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setRowCount(0);
how.res = how.stat.executeQuery("select * from students limit "+numClick+" , 100");
while(how.res.next())
{
String id = how.res.getString(1);
String name = how.res.getString(2);
String contact = how.res.getString(3);
Object[] content = {id,name,contact};
model.addRow(content);
}
}catch (SQLException e){
e.printStackTrace();
}
}
An opinion-tip: Do not swallow exceptions, and do not face any specific type of exception as Exception. In your case, you should be catching them as SQLException and at least print their stacktrace.
Since your first page - query is "select * from students order by name ASC limit 100" the next page - next query should be something like "select * from students order by name ASC limit "+numClick+" , 100" with numClick increased by 100 in every page. Of course numClick variable should be handled by a PreparedStatement. Read here how to use prepared statements.
In order to understand LIMIT take a look at this answered question in addition.
Another way that you could give a chance, if your data is kind of small, is to load everything in memory (a data structure), and then populate the data from there.
When you change page, you will have to current data from the table. A simple search will guide you in this question.
You could use LIMIT 0, 100
SELECT * FROM students ORDER by name ASC LIMIT 0, 100 // Returns 1 -> 100
SELECT * FROM students ORDER by name ASC LIMIT 100, 101 // Returns 101 -> 201
SELECT * FROM students ORDER by name ASC LIMIT 200, 101 // Returns 201 -> 301

Java JDBC - Navigate Through Records Within Database

I am having some trouble in returning the NEXT record within the database, my code currently only returns the last record entered. I have tried creating an instance of a List/ArrayList, tried adding statements to my createStatement(); and just tried everything. I've searched the web, however, I always seem to get the last value returned. I was hoping as to whether someone could help me out. I am using .Swing and this is all executed within an ActionListener.
Essentially I want this function to get the next record in the database. As opposed to returning the last record.
nextEmployee.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Connection connection = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:employeeDatabase.sqlite");
connection.setAutoCommit(false);
System.out.println("Read operation - database successfully opened");
statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
ResultSet resultset = statement.executeQuery( "SELECT * from employees" );
while (resultset.next()) {
ArrayList<Employee> selectAllEmployees = new ArrayList<Employee>();
String id = resultset.getString("id");
String name = resultset.getString("name");
String email = resultset.getString("email");
String gender = resultset.getString("gender");
String dob = resultset.getString("dob");
String Address = resultset.getString("address");
String Postcode = resultset.getString("Postcode");
String NIN = resultset.getString("NIN");
String JobTitle = resultset.getString("JobTitle");
String StartDate = resultset.getString("StartDate");
String Salary = resultset.getString("Salary");
idTextField.setText(id);
nameTextField.setText(name);
genderTextField.setText(gender);
dobTextField.setText(dob);
addressTextField.setText(Address);
postcodeTextField.setText(Postcode);
ninTextField.setText(NIN);
jobtitleTextField.setText(JobTitle);
startdateTextField.setText(StartDate);
salaryTextField.setText(Salary);
emailTextField.setText(email);
}
resultset.close();
statement.close();
connection.close();
} catch ( Exception e1 ) {
System.err.println( e1.getClass().getName() + ": " + e1.getMessage() );
System.exit(0);
}
}});
Thank you for your time and effort.
One of two things is happening. Either:
You have a bug in the code which populates the database, so you think you have rows A, B, and C in the database, but in fact you only have row C
Or:
Your code as listed populates your controls with the contents of row A, then it repeats to populate the exact same controls with contents of row B, and then the exact same controls once more with the contents of row C. So, naturally, the values you are left with are the values of the last row.
It helps to think precisely what it is that you are trying to do, precisely what is happening, precisely what you expected to happen instead, and most importantly, what makes you believe that the code should do that which you expect it to do rather than what it actually does.

Select one random data that have a common characteristic from a sqlite database

I have a database in sqlite that it has questions on it. Each question has a subject, question, answer, and level column. At the moment, I can ask for a subject and it will print me in a textField the question; however, It always selects the same question. How can I choose a random question that belongs to the subject Math?
My code looks like this at the moment:
question = new TextField();
question.setPrefWidth(400.0);
question.setPrefHeight(70.0);
question.setStyle("-fx-font: 30 timesnewroman; -fx-base: #190707;-fx-text-fill: black;");
startTestButton = new Button("START");
startTestButton.addEventHandler(ActionEvent.ACTION, (e)-> {
counterQuestions = nQTextField.getText();
System.out.println("Number of questions: " + counterQuestions);
try
{
String sql = "select * from Questions where Subject = ?";
PreparedStatement pst = connectionQuestions.prepareStatement(sql);
pst.setString(1,SsubjectTestField.getText());
ResultSet rs = pst.executeQuery();
if(rs.next())
{
question.setText(rs.getString("Question"));
}
else
{
System.out.println("No data for this subject");
}
}
catch(Exception a)
{
System.out.println(a);
}
primaryStage.setScene(sceneMathTest);
});
startTestButton.setPrefWidth(200.0);
startTestButton.setPrefHeight(50.0);
startTestButton.setStyle("-fx-font: 30 timesnewroman; -fx-base: #2EFE64; -fx-text-fill: black;");
createTestButtonPane.add(startTestButton,5,6);
THe frase that I use is : "select * from Questions where Subject = ?", however the * means all of them but it is choosing always the same one.
Thank you so much in advance.
You only call rs.next() once so it will only select the first one from the result set. If the database always retrieves them in the same order (which it will), then you will always get the same one. (And, by the way, * here means all columns, not all rows; the rows you get are determined by the where clause.)
If you don't have a large number of data in the database, you can just select everything into a list and choose a random element of the list:
ResultSet rs = pst.executeQuery();
List<String> allQuestions = new ArrayList<>();
while(rs.next())
{
allQuestions.add(rs.getString("Question"));
}
if (allQuestions.isEmpty()) {
System.out.println("No data for this subject");
} else {
Random random = new Random();
question.setText(allQuestions.get(random.nextInt(allQuestions.size())));
}
If you have a very large number of items in the database, this is however a bad option, as you will load them all into memory. In that case you might want to use some SQL tricks to select a specific row from the database. You can get a count of all rows first using
SELECT COUNT(*) FROM Questions WHERE Subject = ?
Then choose a random number between 1 and the returned value and use the techniques in How to select the nth row in a SQL database table? to get that specific row.

Max value from auto commit false table

My problem is i have set a table auto commit false. I need to get the max id from that table(the currently inserted value of auto increment id). But i am getting the id of the previous committed process. Is it possible to get the value
My real problem is i need to insert into table some values, And need to take the id of the last inserted record from the first table and insert it to the second. The second insertion includes some image upload as well(as part of the code). so it take some delay or can have exceptions. I need to undo all insertions(both in the first and second) by occurring any exceptions. I tried to use commit-roll back method for this. But its not properly working as i mentioned above. main portion of my code is written below
try
{
//getting connection and setting auto commit false
dbHandler dbGetConnect=new dbHandler();
Connection conRegPlot=null;
conRegPlot=dbGetConnect.getconn();
conRegPlot.setAutoCommit(false);
String qryInsertPlot="INSERT INTO property_table(name,message,owner,locality,lattitude,longitude,country,state,city,type,catagory,created,modified,creted_date,zoompoint,mob_no,title,img_path,expire_date,lease_term) VALUES('none','"+description+"','"+sessionUserId+"','"+locality+"','"+lattitude+"','"+longitude+"','"+country+"','"+state+"','"+city+"','"+type+"','"+catagory+"',NOW(),NOW(),CURDATE(),'"+zoom+"','"+mob_no+"','"+title+"','NOT IN USE',"+expireDate+",'"+termsAndConditions+"')";//insertion into the first table
Statement stCrs=conRegPlot.createStatement();
int resp=stCrs.executeUpdate(qryInsertPlot);
String qryGetMaxProperty="SELECT MAX(l_id)"+
" FROM property_table"+
" WHERE stat='active'"+
" AND CURDATE()<=expire_date";
propertyId1=dbInsertPropert.returnSingleValue(qryGetMaxProperty);// get the max id
String qryInsertImage="INSERT INTO image_table(plot_id,ownr_id,created_date,created,modified,stat,img_path) VALUES('"+propertyId1+"','"+sessionUserId+"',CURDATE(),NOW(),NOW(),'active','"+img_pth+"')";
Statement stImg=conRegPlot.createStatement();
stImg.executeUpdate(qryInsertImage);// inserting the image
conRegPlot.commit();
}
catch(Exception exc)
{
conRegPlot.rollback();
}
finally{
conRegPlot.close();
}
Since
And need to take the id of the last inserted record from the first
table and insert it to the second.
You could the use of the new JDBC 3.0 method getGeneratedKeys() for get the generated ID. In ahother hand, you should use PreparedStatement for avoid SQL Injection.
PreparedStatement ps = null;
try {
conn = getConnection();
ps = conn.prepareStatement(myQuery, PreparedStatement.RETURN_GENERATED_KEYS);
ps.setInt(1, anInteger);
...
int rows = ps.executeUpdate();
if (rows == 1) {
ResultSet keysRS = ps.getGeneratedKeys();
if (keysRS.next())
int id = keysRS.getInt(1) // Get generated id
For MySQL, see more in http://dev.mysql.com/doc/refman/5.1/en/connector-j-usagenotes-last-insert-id.html#connector-j-examples-autoincrement-getgeneratedkeys

Categories

Resources