How to store the value of resultset as an int? - java

I need to open a div tag from jsp if the value of the resultset is more than 30000. But how to store the value of rs as an int?
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
con = DriverManager.getConnection (urlPrefix, "uname", "pwd");
System.out.println("got connection");
stmt = con.createStatement();
String strQuery = "SELECT count(*) FROM tablename where condition stmt";
rs = stmt.executeQuery(strQuery);
if (rs>30000) {
request.getParameter("view");
}
System.out.println("executed query");
} catch(Exception e) {
System.out.println(e);
}

rs = stmt.executeQuery(strQuery);
stmt.executeQuery return a ResultSet object and from the object we can retrive the result of
the query like below for your case.
rs = stmt.executeQuery(strQuery);
int count=0;
if(rs.next()){
count=rs.getInt(1);
}

Related

java.sql.SQLSyntaxErrorException: Unknown column 'indexno11' in 'where clause'

tu.java
//jdbc connection
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/st","root","root");
//query
String query = "select indexno,lname,fname from reg where indexno= ? and tel=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, Integer.parseInt(in.getText()));
ps.setInt(2, Integer.parseInt(tl.getText()));
ResultSet rs = ps.executeQuery();
if(rs.next()) {
String name11 =rs.getString("lname");
String name1 =rs.getString("fname");
int indexno11 =rs.getInt("indexno");
//passing value to wt frame
wt wt = new wt(name11, name1, indexno11);
wt.show();
}
rs.close();
con.close();`
wt.java
loging page index number used to check next frame credentials
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/st","root","root");
String query = "select age from reg where indexno=indexno11";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
String age11 =rs.getString("age");
System.out.println(age11);
}
rs.close();
con.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
You forgot your literalising single quotes around the value in the String query line.
String query = "select age from reg where indexno='indexno11'";

How to get all the prices from a particular column add them and print them

I have a column name(selling price) in a database which contains all the prices of a product now what i want is to add all the selling prices and display the total selling price.
for example: Selling price column contains
Selling price
-------------
580
580
20
i want to add all the selling prices and display the total in the case the total will be 1180.
try {
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
Statement st = con.createStatement();
ResultSet rs;
String mysqlQuery = "SELECT `sellingprice` FROM cust_info";
rs =st.executeQuery(mysqlQuery);
while(rs.next()) {
String total = rs.getString("sellingprice"); // getting all the selling prices
//converting to integer
int totalValue = Integer.parseInt(total);
// what logic should goes here....
System.out.println(totalValue);
}
}catch(Exception e) {
System.out.println(e.getMessage());
}
You can just use SUM in the query like in the comment above or you can do the following:
try {
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
Statement st = con.createStatement();
ResultSet rs;
String mysqlQuery = "SELECT `sellingprice` FROM cust_info";
rs =st.executeQuery(mysqlQuery);
int totalValue = 0;
while(rs.next()) {
totalValue += rs.getInt("sellingprice");
}
System.out.println"The total Value is: " + totalValue;
}catch(Exception e) {
System.out.println(e.getMessage());
}
I changed the following
rs.getInt instead of rs.getString , you can also use getDouble depending on the data you are expecting.
declare and initialize the int variable before the loop and increment it within the loop.
print the total after the loop has finished.
try {
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
Statement st = con.createStatement();
ResultSet rs;
String mysqlQuery = "SELECT `sellingprice` FROM cust_info";
rs =st.executeQuery(mysqlQuery);
while(rs.next()) {
String total = rs.getString("sellingprice"); // getting all the selling prices
//converting to integer
int totalValue = Integer.parseInt(total);//<----- YOUR PROBLEM
// what logic should goes here....
System.out.println(totalValue);
}
}catch(Exception e) {
System.out.println(e.getMessage());
}
You can't create your totalValue in your while statement. Each time the code cycles through the while statement, you're going to reset the total value to the latest total you got from your resultset. You want something like:
try {
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
Statement st = con.createStatement();
ResultSet rs;
String mysqlQuery = "SELECT `sellingprice` FROM cust_info";
rs =st.executeQuery(mysqlQuery);
int totalValue = 0; //<-- Create your total value outside of the while statement.
while(rs.next()) {
String total = rs.getString("sellingprice");
totalValue += Integer.parseInt(total);//<-- Add the selling price from the current row to the total.
System.out.println(totalValue); //<--This will print the latest total for each row in your result set
}
System.out.println(totalValue); //<-- This will print only the final total
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
Try this solution , using the SUM function :
try {
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
Statement st = con.createStatement();
ResultSet rs;
String mysqlQuery = "SELECT SUM(`sellingprice`) FROM cust_info";
rs =st.executeQuery(mysqlQuery);
int totalValue = 0;
if(rs.next()) {
String total = rs.getString("sellingprice");
if(total != null){
totalValue = Integer.parseInt(total);
}
System.out.println(totalValue);
}
}catch(Exception e) {
System.out.println(e.getMessage());
}

How do I return the contents of a ResultSet as a map?

I would like to know how I can return a result set from a query as a map.
This is my query where 'nameCodesString' is a list of strings e.g. ('raul', 'peter', 'shawn'):
try (PreparedStatement stmt = conn.prepareStatement("select n.CODE, l.VALUE"
+ " from TNAME n join TPROPERTIES l on n.UIDPK = l.OBJECT_UID"
+ " where n.CODE IN (" + nameCodesString + ")")) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
log.info("rs {}",rs);
nameCode = rs.getString(1);
displayName = rs.getString(2);
Person.add(new PersonDTO(nameCode, displayName, ""));
}
}
}
The result should be a code and a value. I am not sure how I can do this all in one connection to the database.
Hello that is my suggestion
String req="select n.CODE, l.VALUE from TNAME n join"
+" TPROPERTIES l on n.UIDPK = l.OBJECT_UID "
+" where n.CODE IN ?";
PreparedStatement stmt=null;
ResultSet rs=null;
try{
stmt=conn.prepareStatement(req);
stmt.setString(1, nameCodesString);
rs=stmt.executeQuery();
while(rs.next()){
nameCode = rs.getString(1);
displayName = rs.getString(2);
Person.add(new PersonDTO(nameCode, displayName, ""));
}
}
catch(SQLException ex){
System.out.println(ex);
}
finally{
if(rs!=null){
try{
rs.close();
}
catch(SQLException ex){}
}
if(stmt!=null){
try{
stmt.close();
}
catch(SQLException ex){}
}
if(conn!=null){
try{
conn.close();
}
catch(SQLException ex){}
}
}
It is just my suggestion i hope it can be a tip for you!
Best regards...
I failed to understand how preparedStatements should be used. In the end I decided not to use them and stick to executing a query string:
Map<String, String> personDetails = new Hashmap();
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select n.CODE, l.VALUE"
+ " from TNAME n join TPROPERTIES l on n.UIDPK = l.OBJECT_UID"
+ " where n.CODE IN (" + nameCodesString + ")")) {
while (rs.next()) {
nameCode = rs.getString(1);
displayName = rs.getString(2);
personDetails.put(nameCode, displayName);
}
}

Data not displayed in jList method from database

I am Using the following code :
DefaultListModel dModel = (DefaultListModel)jList1.getModel();
txtBilln.enableInputMethods(false);
try{
Class.forName("com.mysql.jdbc.Drvier");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/jns","root","jns");
Statement stmt = null ;
ResultSet rs = null ;
String SQL = "SELECT * FROM ELEB";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()){
String bno= rs.getString("billn");
String cnamme = rs.getString("cname");
dModel.addElement(bno + "-" + cnamme);
}
jList1.setModel(dModel);
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
e.printStackTrace();
}

Can we use two queries using prepared statement in one method

Can we use two queries in one method while using prepared statement, I have tried using this but invalid column name exception is coming.
My code snippets is as follows.
public double getPayroll(){
ResultSet rs = null;
ResultSet rs2 = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getDBConnection();
int employeeId;
String q1 = "select e_salary,e_house_rent,e_conv_allow,e_id
from employee";
pstmt = conn.prepareStatement(q1);
rs = pstmt.executeQuery();
double dailyPay=0,basicPay=0,payroll2=0;
int houseRent=0,convAllow=0;
while (rs.next()) {
dailyPay = rs.getInt(1)*.03;
houseRent=rs.getInt(2);
convAllow=rs.getInt(3);
employeeId=rs.getInt(4);
}
String q2="select att_status from attendance where
e_id=employeeId";
pstmt = conn.prepareStatement(q2);
rs2 = pstmt.executeQuery();
int noOfPresents = 0;
while(rs2.next()){
noOfPresents+=1;
}
basicPay=dailyPay*noOfPresents;
payroll2+=basicPay+houseRent+convAllow;
return payroll2;
} catch (Exception e) {
e.printStackTrace();
return 0.0;
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Your problem is that the sql in q2 assumes that there is a column named employeeId, but I suspect you want to insert the value of the variable employeeId.
Change it to
select att_status from attendance where e_id=?
Then execute
pstmt.setString(1, employeeId);
before executing pstmt.executeQuery();

Categories

Resources