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");
Related
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.
I have a table called Rooms and this how the table looks like
CREATE TABLE Rooms
(
id INT AUTO_INCREMENT,
RoomNumber VARCHAR(32) NOT NULL,
AvailableSeats INT NOT NULL,
PRIMARY KEY (id)
)
In my code below, i am able to fill the combo box with the room numbers in the database. But what i want to do is, when i select a room number, the available seats for that room number must update.
For instance, when i select
RoomNumber 4, available seats 4
RoomNumber 3, available seats 2
How can i achieve this ?
Query
// query to fetch room numbers to combo box
public void FindRoom() {
String query = "Select * from Rooms";
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
String getRoomNumber = rs.getString("RoomNumber");
FindRoom.addItem(getRoomNumber);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
//query to get respective available seats for every room number
public void FindSeats() {
String query = "Select * from Rooms where RoomNumber = "+FindRoom.getSelectedItem();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
String getAvailableSeat = rs.getString("AvailableSeats");
seats.setText(getAvailableSeat);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
UPDATE
i changed sql query (just test it and it works on sql but still not working with java dont no why :(
Hi how to add get result on jLabel with this code? and is it possible to show results on jTable?
private void searchTeacherActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = ("select student_ID, firstName, afterName FROM student JOIN studentHom ON course = studentHom_ID WHERE prefect = ?
try {
pst = connection.prepareStatement(sql);
pst.setString(1, larareSoka.getText());
pst.execute();
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, e);
}
}
First don't use (?) you can just use ?:
select ... where course.courseStart = ? and course.corse.end = ?
Second you have to set parametters to your query in your case you have tow, so you have to use :
pst.setString(1, value_of_courseStart);
pst.setString(2, value_of_corse.end);
Third to get results you have to use ResultSet like this :
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
String firstname = result.getString(1);
//----------------------------------^
//...same for the other columns
}
or you can use the name of column like this:
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
String firstname = result.getString("firstName");
//--------------------------------------^^
//...same for the other columns
}
Note
If you want to get multiple result you ca use while instead of if.
Your query is a little wired why you are using :
course.courseStart = (?) and course.corse.end = (?)
//no point---^ ^------Why this point here
Did you mean course.courseStart = ? and course.corseEnd = ?
ResultSet rs = pst.executeQuery();
String firstname = rs.getString("firstname");
..
jLable.setText(firstname);
...You need to read the data from the resultset
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.
Can you populate more than one jTable with the same resultSet?
public void tableDisplay() {
String tableQuery = "SELECT foodQuantity,foodName FROM food ORDER BY RAND() LIMIT 3";
ResultSet rs;
PreparedStatement statement;
try {
statement = con.prepareStatement(tableQuery);
rs = statement.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
System.out.println(ex.toString());
}
}
The code compiles but the second table doesn't get any records from DB.
The point is that I need to select random items from mySql table and I want to display them in few jTables.
Without knowing too much about your code, I'd say that you need to call DbUtils.resultSetToTableModel(rs) once, and store the resulting table model in a local variable. Then, pass that local variable to the two setModel(...) methods
How I populate a JTable with resultSet
try{
playerTableModel = (DefaultTableModel)playerTable.getModel();
rs = controller.getPlayer();
while (playerTableModel.getRowCount() > 0);
int columns = playerTableModel.getColumnCount();
Object[] rows = new Object[columns];
while(rs.next()){
rows[0] = rs.getString(1);
rows[1] = rs.getString(2);
rows[2] = rs.getString(3);
rows[3] = rs.getString(4);
playerTableModel.addRow(rows);
}catch(Exception e){
e.printStackTrace();
}
Can't you just call same method for the second table too?