Can we use two queries using prepared statement in one method - java

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();

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'";

Having Trouble filling a LocalDateTime array with data from MySQL database

I'm using a MySQL database to hold information for my reminder application in Java. I'm trying to pull the information out and store it in an array and the compare each element of the array to an updating current timestamp. The issue is the code I have gives a nullpointer exception and I can't figure out why. It works when the LocalDateTime isn't an array but the moment I turn it into an array it throws the error. It also demands I initialize it to null over anything else.
Thoughts on how I can fix this? Any help is appreciated.
Here's the method in question.
public static LocalDateTime[] getReminderTime()
{
String SQL = "SELECT r_dateTime FROM reminder_database.reminder;";
LocalDateTime reminderTime[] = null;
try
{
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
if(rs.isBeforeFirst())
{
for(int i = 0; rs.next(); i++)
{
reminderTime[i] = rs.getTimestamp(1).toLocalDateTime();
}
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Exception thrown with getReminderTime --> " + e + e.getStackTrace());
}
return reminderTime;
}
Heres the exception thrown
Exception thrown with getReminderTime --> java.lang.NullPointerException[Ljava.lang.StackTraceElement;#6dfc1e5f
Exception thrown with getReminderTime --> java.lang.NullPointerException[Ljava.lang.StackTraceElement;#3b2da18f
Found a solution.
I needed to initialize a size for the array in order to fill it. So I created another method that went through all the elements and gets the size.
Here's the code.
public static LocalDateTime[] getReminderTime()
{
String SQL = "SELECT r_dateTime FROM reminder_database.reminder;";
LocalDateTime reminderTime[] = null;
reminderTime = new LocalDateTime[getSizeOfRs()];
try
{
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
if(rs.isBeforeFirst())
{
for(int i = 0; rs.next(); i++)
{
reminderTime[i] = rs.getTimestamp(1).toLocalDateTime();
}
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Exception thrown with getReminderTime --> " + e + e.getStackTrace());
}
return reminderTime;
}
and the get rs size
public static int getSizeOfRs()
{
String SQL = "SELECT * FROM reminder_database.reminder;";
int size = 0;
try {
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
for(int i = 0; rs.next(); i++)
size++;
}
catch(Exception e)
{
System.out.println("Exception thrown with getSizeofRS --> " + e + e.getStackTrace());
}
return size;
}

java resultSet not updatable

i have a problem in resultset when i made update on value inside database and i have primarykey inside my db
this is the exception that i have
com.mysql.jdbc.NotUpdatable: Result Set not updatable
protected void processPairWords()
{
int count1=0;
try {
Statement st1;
Statement st2;
st1 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
st2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet res1 = st1
.executeQuery("SELECT txt,freq,prob FROM searchtb WHERE txttype=1");
ResultSet res2= st2
.executeQuery("SELECT txt,freq,prob FROM searchtb WHERE txttype=2");
res1.beforeFirst();
res2.beforeFirst();
while (res1.next()){
while(res2.next())
{
if(res2.getString("txt").startsWith(res1.getString("txt")))
{
int prob2=res2.getInt("freq");
int prob1=res1.getInt("freq");
double prob=prob2/prob1;
res2.updateDouble("prob", prob);
res2.updateRow();
count1++;
System.out.println(res2.getString("txt"));
} }
System.out.println("loop1");
}
conn.commit();
System.out.println("pairs count"+count1 );
} catch (SQLException e) {
e.printStackTrace();
}
}
I think the table should have a primary key and the SQL query should select it.
Hope this can help you.

How to store the value of resultset as an int?

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);
}

how to check database table is empty or not

i have a database with a table 'admin'.But presently just creating table not having any values.table columns are user_name and password.My motive is to check whether the table is empty or not.I am using mysql database.I tried following code and its fails.Please help me.
public void nullCheck() {
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT * From admin ";
try {
stmt = (PreparedStatement) conn.prepareStatement(qry);
rs = stmt.executeQuery();
boolean empty = true;
while( rs.next() ) {
// ResultSet processing here
empty = false;
}
if( empty ) {
Util.showWarningMessageDialog("null");
}
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you just need to check the table then you should use query:
String qry = "SELECT count(*) From admin ";
for better performance.
And get the row count from ResultSet to check the table is null or not.
int count=0;
while( rs.next() )
{
count=rs.getInt("count");
}
Try this code, I think this will do it. I updated it coz the first I post here is not working at all, my bad.
public void nullCheck() {
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT * From admin ";
try {
stmt = (PreparedStatement) conn.prepareStatement(qry);
rs = stmt.executeQuery();
int count = 0;
while(rs.next()){
count++;
}
if(count == 0){ // if equal to 0 then the table is null
bla bla bla
}
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}

Categories

Resources