I'm having trouble convert this String sql results into int. Can you guys tell how to accomplish this.
I'm doing this because I need this value set in to a JLabel that shows attendance count.
I've tried to search for the answer here, but I couldn't find it. Please can you guys help me with this problem?
public static int attendanceCount() throws ClassNotFoundException, SQLException {
String sql = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
Statement stm = conn.createStatement();
ResultSet rst = stm.executeQuery(sql);
return rst; // How do I convert this into integer?
}
This is what I need to accomplish.
private void setAttendanceTile() {
try {
int attendanceCount = AttendanceController.attendanceCount();
inHouseMembersLabel.setText(Integer.toString(attendanceCount));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
Or is there another way to accomplish this without doing this way?
Thanks.
get ResultSet.getInt(1):
int id = rst.getInt(1);
You could use ResultSet.getInt() method. It takes either a column index or a column name. Here's an example from Oracle.
In your case you would need the one which takes the index (note that index starts with 1, not 0).
As suggested earlier, try using .getInt() method.
Moreover, I would use PreparedStatement. It's important to use PreparedStatement, because it allows database to cache your queries.
Also, always close your Connection and ResultSet after using them.
public static int attendanceCount() throws ClassNotFoundException, SQLException {
final int COLUMN_NO = 1;
final String SQL = "select count(accountNo) from attendance";
Connection conn = DBConnection.getDBConnection().getConnection();
PreparedStatement stm = conn.prepareStatement(SQL);
ResultSet rst = stm.executeQuery();
int result = rst.getInt(COLUMN_NO);
try {
rst.close();
conn.close();
} catch (SQLException e) {} //ignore
return result;
}
Related
#Override
public void start(Stage primaryStage) throws Exception{
try{
String fxmlName;
Connection con = DriverManager.getConnection("url","root","password");
Statement st = con.createStatement();
String qry = "select UpdateT from schema.update";
ResultSet rs = st.executeQuery(qry);
fxmlName = rs.getString("UpdateT");
// System.out.println(fxmlName);
st.close();
Parent root = FXMLLoader.load(getClass().getResource(fxmlName));
primaryStage.setScene(new Scene(root));
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.show();
}
catch (Exception e){
System.out.println(e);
}
}
Hey guys this is my code and its my first time on stack overflow and why I am getting this exception?
java.sql.SQLException: Before start of result set
UPDATE is a reserved word, so your DB objects should not use it. You can:
change the table name (i 'd prefer this)
use quotes every time to refer to that table
My code works fine but when I try to run the code it first shows java.sql.SQLException:After end of result set. I would like to know what is causing this and how to fix this as this is for a graded project.
public GenerateBill()
{
initComponents();
try
{
Class.forName("java.sql.DriverManager");
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore","root","root");
Statement stmt=(Statement)con.createStatement();
String query, product;
query="select * from store;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next());
{
product=rs.getString("productname");
jComboBox1.addItem(product);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.toString());
}
}
When I execute the code a Message Dialog Box shows up first.
And when I click OK, the page I'm trying to make opens and executes normally.
So, I'm confused as to what it means. Also, I'm new to this site, so I don't really know how much of the code I need to add. The rest of the code is for different jButtons. The page is for Generating Bills/Receipts.
There are some parts in your code that could be better. Specifically,
Use com.mysql.jdbc.Driver as your DB is MySQL, instead of java.sql.DriverManager
No need to cast your Connection object.
After /bookstore you could add ?useSSL=false, although it is not mandatory, so something like jdbc:mysql://localhost:3306/bookstore?useSSL=false
Use java.sql.PreparedStatement instead of simply Statement.
Close your connection in a finally block after catch.
Eventually, your code should look somehow like the following,
public GenerateBill() {
initComponents();
Connection con = null;
ResultSet rs = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore?useSSL=false","root","root");
String query = "select * from store";
stmt = con.prepareStatement(query);
String product;
rs = stmt.executeQuery();
while(rs.next())
{
product = rs.getString("productname");
jComboBox1.addItem(product);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.toString());
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
LOG.error("Error closing the connection with the database...");
e.printStackTrace();
}
}
}
Try the above and let me know if it is OK. If not, please post the whole exception to see what causes the issue.
I'm trying to update one row in my db using Query but I have no idea why it doesn't work.
I use this method:
#Override
public void updateImage(String avatar, int employeeId) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
Transaction transaction = null;
Query query = session.createQuery("UPDATE vt_employee SET emp_avatar=? WHERE id_employee=?");
query.setString(0, avatar);
query.setInteger(1, employeeId);
transaction = session.beginTransaction();
query.executeUpdate();
transaction.commit();
} catch (Exception e) {
e.getStackTrace();
} finally {
session.clear();
}
}
My values avatar and employeeId of course are not null or empty I checked it by display in console. My table in db is vt_employee and fields like emp_avatar and id_employee exist.
I checked in which place is problem and problem is in createQuery, if I tried to display arguments before session.createQuery then they displayed in console but after this one line they don't.
Could someone help to solve this problem?
Can you try with this.
public void updateImage(String avatar, int employeeId) {
String hql = "UPDATE vt_employee set emp_avatar =:avatar WHERE id_employee =:employeeId";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("avatar",avatar);
query.setParameter("employeeId",employeeId);
int i = query.executeUpdate();
if (i > 0) {
System.Out.println("Updated..") ;
}
}
My code currently goes as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
String[] data = parentIds.toArray(new String[parentIds.size()]);
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (?)";
stmt = conn.prepareStatement(sql);
data = parentIds.toArray(data);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
However even though in the unit tests I try to pass an array with parentIds, the return remains null.
What I can gauge from this is one of the following:
The array data isn't getting properly read, therefore the output is coming as null.
WHERE IN is not supported by h2 or else there is a different implementation that needs to be used instead.
Where am I going wrong in this?
EDIT - There was a similar duplicate question that was tagged. While it suggested using a StringBuilder and a loop, I was looking for an answer stating how it could be done in a cleaner way using the query itself.
Try setting the parameter as a list instead of an array, ie replace
stmt.setObject(1, data);
with
stmt.setObject(1, Arrays.asList(data));
Figured it out.
There was an issue posted on the h2database GitHub about this exact problem. Followed the suggested edits and it worked!
Code after edits is as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
Object[] data = parentIds.toArray();
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (SELECT * FROM TABLE(x VARCHAR = ?))";
stmt = conn.prepareStatement(sql);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
As you can see, I've used an Object array for data instead and added an additional query inside the main query.
Followed the instructions given in the GitHub issue to a tee and it worked flawlessly.
I have a MySQL database in NetBeans.
When I add new data in my database by insert button, I can see my new data in output windows (because I have a code to print all data in database), but I don't know why I can't see my new data in textboxes, it means when I navigate fields by next, previous buttons I can't see my new data !!!!!!
But, when I close the program and run it again, my textboxes show my new data !
What's reason???????
my Next button code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
if (rs.next()) {
int x = Integer.parseInt(rs.getString("id"));
String s = rs.getString("name");
String n = rs.getString("profession");
txtID.setText(Integer.toString(x));
txtName.setText(s);
txtProfession.setText(n);
} else {
rs.previous();
}
} catch (Exception e) {
System.out.println(e);
}
}
My insert button code :
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO sample (id,name,profession) VALUES ('"+txtID.getText()+"','"+txtName.getText()+"','"+txtProfession.getText()+"');");
st.executeQuery("Select * from sample");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
Help me please.
assuming ResultSet rs is a class level variable, with in your method jButton3ActionPerformed() change the following
st.executeQuery("Select * from sample");
to
rs = st.executeQuery("Select * from sample");
one suggestion is, you should close your database resources once you fetch the data and you can construct your Collection to hold the data for further processing.
The pagination that you are trying to use is not good practice