Retrieving the maximum value from an Integer column in an Access table - java

I have a textfield in a NetBeans frameform. I added a "Generate" button, and when I click it the program should find the largest value from the column "book_code" in a table named "books" and should display "generated value+1" in the textfield.
I use a class method to connect to my database so you won't find any code for connecting the database.
I have tried some coding but I am not able to generate the maximum value from book_code column of table books. Here is what I did:
String b_code="select max(Book_code) from books";
try
{
pst = conn.prepareStatement(b_code);
rs=pst.executeQuery();
int a=rs.getInt(b_code);
System.out.println("Book code is "+a);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null , e);
}
The maximum value in book_code column is 103, and when I click the "generate" button I would like to see 104 in the textfield.

There are at least two (2) issues with your code:
You create your ResultSet but you don't call rs.next() before you try to retrieve the value.
When you do try to retrieve the value you use the variable that contains the SQL string, and there is no column in the ResultSet that matches
This should work better:
String b_code="select max(Book_code) from books";
try {
pst = conn.prepareStatement(b_code);
rs = pst.executeQuery();
rs.next();
int a = rs.getInt(1);
System.out.println(String.format("max(Book_code) is %d", a));
} catch(Exception e) {
JOptionPane.showMessageDialog(null , e);
}

Related

Get next record from SQLite database when button is clicked

I have read notes about this but none seems to work for me. I have an SQLite database and with Netbeans as my IDE, I have a jframe that displays data records in a jtable, with records displayed in ascending order. Clicking on a record displays them in jtextfields.
I want to move to next record in database in ascending order when I click on a button, but it doesn't seem to work. What am I doing wrong?
try{
String sql ="select * from Employees order by Name ASC";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
int i = rs.getInt("ID");
String idi= Integer.toString(i);
id.setText(idi);
String a = rs.getString("Name");
name.setText(a);
String b = rs.getString("Contact");
contact.setText(b);
String c = rs.getString("Email");
email.setText(c);
String d = rs.getString("Residence");
residence.setText(d);
String e = rs.getString("Job_Type");
comboJob.setSelectedItem(e);
}
else {
rs.previous();
}
}
catch(SQLException | HeadlessException ex)
{
JOptionPane.showMessageDialog(null, ex);
}finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
}
}
you need to store the values from database in an array and then iterate over it with your (prev,next) button like
i=0;
while(rs.next()) {
dataset["ID"][i]=Integer.toString(rs.getInt("ID"));
dataset["Name"][i]=rs.getString("EName");
i++
}
to display information you can use dataset array like
id.setText(dataset["ID"][i]);
name.setText(dataset["EName"][i]);
not checked syntax but the logic is correct.

How to call the result of a consult and put it in a Textfield? Mysql + Java

my textfield is called pruebamax
With this function I make the connection with the database
public ResultSet getmax() {
ResultSet r = null;
try {
String sql = "select count(*) as Cantidad from tbl_padre";
System.out.println(sql);
Statement st = cx.createStatement();
r = st.executeQuery(sql);
System.out.println(st.executeQuery(sql));
} catch (SQLException ex) {
Logger.getLogger(Tmrptryone.class.getName()).log(Level.SEVERE, null, ex);
}
return r;
}
his method in the event of a button, with this method I want to print in the textfield the data I receive from the database but I got an error.
public void actualizatext() {
try {
ResultSet r = mrp.getmax();
if (r.next()) {
String ID = r.getString("Cantidad");
pruebamax.setText(ID);
}
} catch (SQLException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
Now, I don't know what pruebamax means but the SQL statement you used:
String sql = "SELECT COUNT(*) AS Cantidad FROM tbl_padre";
is specifically used to count the total number of records currently maintained within the specified database table (tbl_padre). The value from that count will be held in the specified temporary field named: Cantidad. When you Use the SQL COUNT statement you are not going to be returned a String data type value. You will be expected to try and acquire a Integer value.
It will not acquire a value from your table ID field as what it looks like you expect.
To properly retrieve the records count from your applied SQL string then it should be used in this fashion:
int count = 0;
try {
String sql = "SELECT COUNT(*) AS rCount FROM tbl_padre";
Statement st = cx.createStatement();
ResultSet r = st.executeQuery(sql);
while (r.next()) {
count = r.getInt("rCount");
}
r.close();
st.close();
// Close your DB connection as well if desired.
// yourConnection.close();
//To apply this value to your JTextField:
pruebamax.setText(String.valueOf(count));
System.out.println("Total number of records in the tbl_padre " +
" table is: " + count);
}
catch (SQLException ex) {
ex.printStackTrace();
}
Try not to use actual table field names for temporary field names.
If you want to be more specific with your count then your SQL statement must be more specific as well. For example, let's assume that we want to count the number of records maintained in our table where a field named Age contains a value which is greater than 30 years old, our sql statement would look like this:
String sql = "SELECT COUNT(*) AS rCount FROM tbl_padre WHERE Age > 30";
You will of course have noticed the use of the SQL WHERE clause.

How to get value from database into int java

I created a program where I need to parse and value from database into integer and put it to JLabel, the problem is that showed value is always 0, but when I check statement in database it shows the right value.
code:
try {
conn = DriverManager.getConnection("database....");
stat = conn.createStatement();
result = stat.executeQuery("statement...(works fine) ");
integerx = ((Number) result.getObject(1)).intValue();
result.close();
stat.close();
}catch (Exception e){
}
label.setText("the value is : " + integerx );
How can I get the value from database? The data is limited to show 1 column and 1 row.
integerx = result.getInt(1); // if the data exist on the first column

how to get the product of two columns in a table?

I am developing a GUI Desktop application using Netbeans. I have made a veriable for the total which does not show the result. Please check out the coding weather if there are some changes to do or if is it wrong. When I execute it, in column 3 it shows error and there is no result
private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {
Connection con;
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbc");
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex);
}
try {
con= DriverManager.getConnection("Jdbc:Odbc:food");
stmt= con.createStatement();
String st= JcbSub.getSelectedItem().toString();
String qt= quantity.getText().toString();
String query;
Double u_p= (Double) jTable3.getValueAt(row, 1);
Integer qut= (Integer) jTable3.getValueAt(row, 2);
Double tot= u_p * qut; //product of column 1 & column 2
query="select i_price from food where i_name='"+JcbSub.getSelectedItem()+"'";
ResultSet rs= stmt.executeQuery(query);
while(rs.next()){
jTable3.setValueAt(st, row, 0);
jTable3.setValueAt(rs.getString("i_price"), row, 1);
jTable3.setValueAt(qt, row, 2);
jTable3.setValueAt(tot, row, 3); //result column
row ++;
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
actually the values in column 1 is selected from the database table and and column 2 values are entered manually using jTextField and transferred to column 2
Extend your TableModel and override the setValueAt() method.
Whenever the value in column 1 or 2 changes (and both contain non-null values) you should calculate the product and update column 3.
Don't do java, but use a parameterised query and for instance do something like
query="select name, i_price, #qty,#total, #qty*#total from food where i_name=#name"
add the parameters to the query, set their values to qt, tot and st, and Bob is your mothers sister's brother, and you don't have a potential sql injection attack as well...
OWASP guidance Java parameterised queries

how to set values from database into the textfield

private void btgetinvActionPerformed(java.awt.event.ActionEvent evt) {
//JOptionPane.showMessageDialog(null, "REMITTANCE ID IS VALID!");
try {
DBUtil util = new DBUtil();
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement("select bk_det.rm_id from bk_det WHERE dbo.bk_det.rm_id = ?");
ResultSet rs;
String rm = tf_rmid.getText().trim();
stmt.setInt(1, Integer.parseInt(rm));
rs = stmt.executeQuery();
while (rs.next()) {
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
I am actually trying to search value from my database table called dbo.bk_det. I am taking the value of WHERE from my textfield tf_rmid. Everything goes on well without error but once i insert the rm_id and click on button btgetinv it says 123 which is my rm_id is out of range cant understand where the error is and what is the problem.
The problem is with the following statements:
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
The first statement won't work the way you want because there's no column named "box_no" in the select clause. It will throw an exception. Let's assume you change the code to have box_no in the select clause. Then, the second statement will try to retrieve the nth column where the column is the value of box_no. I think you just want:
tfbrname.setText(rs.getString("box_no"));
Again, the above only will work if your SELECT statement includes box_no in the field list.
rs.next() returns false if it does not contain any more records. So if you want to behave something when no records found, you have to check record count.
for example,
int recordCount = 0;
while (rs.next()) {
recordCount++;
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
if(recordCount == 0) {
// do something : report an error or log
}
for further information, see http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#next()

Categories

Resources