Retrieve maximum value from database and displays in JTextfield in java eclipse - java

I want to extract maximum value from database and displays in JTextfield in Java. I tried the code shown below. But I get error _No such column 'Enquiry No'.
But 'Enquiry No' colum name is available in enquiry table
Enquiry No is column name
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
try {
String query = "Select max(`Enquiry No`) from enquiry ";
PreparedStatement pst = conn.prepareStatement(query);
// pst.setString(1,textField.getText());
ResultSet rs = pst.executeQuery();
while (rs.next()) {
textField.setText(rs.getString("Enquiry No"));
}
} catch (Exception f) {
f.printStackTrace();
}
}
}

To get max or min, avg, count or any aggregate functions you have to :
put your result as a value and get it like this :
String query="Select max(`Enquiry No`) as max from enquiry ";
...
textField.setText(rs.getString("max"));
Or get the first result like this :
String query="Select max(`Enquiry No`) from enquiry ";
...
textField.setText(rs.getString(1););

Related

Getting Multiple Data using Text field + Jbutton from SQL Server to Jtable

Good day, just wanna ask. I have a Java GUI where I want to add multiple data from SQL server to my Jtable. The flow here is that I would want to use the text field as search field where I will add the info for searching and use the Jbutton to perform the search action then it will give/show me the data to my Jtable. Actually the code is running however some of the data like the 1st data added to my SQL serve and from data id 7 and and up are not showing. How would I fix this and show multiple data with same order ID form SQL server?
Thank you!!
try {
String query = "select * from `sales_product` where order_id = ?";
pst = con.prepareStatement(query);
pst.setString(1, txsearch.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()) {
while(rs.next()) {
String prodname = rs.getString("prodname");
String price = String.valueOf(rs.getInt("price"));
String qty = String.valueOf(rs.getInt("qty"));
String total = String.valueOf(rs.getInt("total"));
model = (DefaultTableModel) datatable.getModel();
model.addRow(new Object[]{
prodname,
price,
qty,
total
});
int sum = 0;
for (int a = 0; a < datatable.getRowCount(); a++) {
sum = sum + Integer.parseInt(datatable.getValueAt(a, 3).toString());
}
Ltotal.setText(Integer.toString(sum));
}
}
else {
JOptionPane.showMessageDialog(this, "No order found!");
txsearch.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(milktea.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(rs.next()) {
while(rs.next()) {
No need for the if (rs.next()) statement. That is causing you to skip the first row of data in the ResultSet.
All you need is the while (rs.next()) statement to create the loop to read all rows in the ResultSet.

How to Count all row in the table using java and mysql

I want to Count all the rows in the table using java and display the count of all the rows in the textfield. I need the count of employee from the table. I have attached below the code and the query used to achieve this. I received the error of the below code Column 'id' not found. error displayed
public void Customer()
{
try {
pst = con.prepareStatement("SELECT COUNT(*) FROM customer");
ResultSet rs = pst.executeQuery();
while(rs.next())
{
String id1 = rs.getString("id");
txtmsg.setText(id1);
}
} catch (SQLException ex) {
Logger.getLogger(gsm.class.getName()).log(Level.SEVERE, null, ex);
}
}
There clearly is no "id" column in your select. You could either get the result by column number like so:
int count = rs.getInt(1);
Or you could use an alias for the column and get result by that name, eg.:
pst = con.prepareStatement("SELECT COUNT(*) AS customerCount FROM customer");
int count = rs.getInt("customerCount");

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.

Sqlite Column Determination Error

I'm trying to get selection from J combo Box and use that to find table from the data base. But instead an error comes up:
My codes it:
JButton btnGo = new JButton("Go!");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Connection conni = null;
ResultSet rs=null;
PreparedStatement pst=null;
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String x = comboBox.getSelectedItem().toString();
String sql="select * from " + x;
pst=conni.prepareStatement(sql);
rs=pst.executeQuery();
while(rs.next()){
String name = rs.getString("Namet");
nameofguy.setText(rs.getString(name));
}
}catch(Exception i){
JOptionPane.showMessageDialog(null, i);
}
I'm searching for table.. but it says cannot find column.
Here's your problem
while(rs.next()){
String name = rs.getString("Namet");
//rs.getString returns Ayaan. So value of name is "Ayaan"
nameofguy.setText(rs.getString(name));
// Youre trying to get the value corresponding to the column Ayaan here
//This is why the exception is thrown as there is no column called Ayaan
}
Instead do
while(rs.next()){
String name = rs.getString("Namet");
nameofguy.setText(name);
}

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