Assign to string instead of resultset for jdbc query - java

I need to get the output of a jdbc query, but wherever I google, it returns a resultset. But, its just a single row. Here is my query
ResultSet rsLocationId = null;
rsLocationId = stmtLocation.executeQuery("SELECT apmcid FROM userbusinesstoapmc WHERE userbusinessid='"+userBusinessKey+"'");
It should return a single record as a string. How can I convert it? Any ideas would be greatly appreciated.

I suggest you use PreparedStatement and bind the parameter, currently you are vulnerable to SQL Injection attacks.
PreparedStatement ps = null;
ResultSet rs = null;
String result = null;
final String sql = "SELECT apmcid FROM userbusinesstoapmc "
+ "WHERE userbusinessid=?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, userBusinessKey);
rs = ps.executeQuery();
if (rs.next()) {
result = rs.getString("apmcid");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

you can try like this
ResultSet rsLocationId = null;String result="";
rsLocationId = stmtLocation.executeQuery("SELECT apmcid FROM userbusinesstoapmc WHERE userbusinessid='"+userBusinessKey+"'");
if(rsLocationId.next())
{
result=rsLocationId.getString('apmcid');
}

Even though your particular query only returns a single column, presumably some CHAR type if you expect the result to be a String, the executeQuery method returns a result set object, not a String object. So, you have to process the result set to get your String data. SpringLearner has provided a good example of how to do this.

Related

How to store output of MySQL command into a java variable (JDBC)

I was wondering how to issue a MySQL command that checks if a table within my database is empty and then subsequently store the boolean result into a java variable. I am trying to use JDBC commands to do this.
This is what I have so far but it is not working properly:
#Override
public boolean isEmpty(Connection connection) {
Statement statement = null;
ResultSet resultSet = null;
Boolean var = true;
try {
statement = connection.createStatement();
System.out.println(statement.execute("SELECT EXISTS (SELECT 1 FROM Persons) AS OUTPUT"));
if(statement.execute("SELECT EXISTS (SELECT 1 FROM Persons)")) {
var = false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return var;
}
When I run the program with a completely new, unpopulated mySQL table, the function returns true. Does anyone know a solution?
Your test checks if the table exists, instead you want to see if the table contains any rows. In order to do so, select the count of rows from the table and verify it is greater than 0. Prefer PreparedStatement over Statement (it's more efficient and performant), and you need a ResultSet to actually iterate the result from the server. Something like,
#Override
public boolean isEmpty(Connection connection) {
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean res = false; // no need for the wrapper type here.
String sql = "SELECT COUNT(*) FROM Persons";
try {
statement = connection.prepareStatement(sql);
System.out.println(sql);
resultSet = statement.executeQuery();
if (resultSet.next()) {
res = resultSet.getInt(1) > 0;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return res;
}
Changed var to res because (as of Java 10) var is now a keyword in Java.
As you are executing a select statement, instead of using Statement.execute(..), you should use Statement.executeQuery(..) and iterate over its result set.
The boolean return value from execute(..) indicates if the first value is a result set or not. It is not the boolean column from your query. You should normally only use execute(..) if you don't know what type of statement it is, or if it is a statement that can produce multiple results (update counts and result sets).
So, instead use:
boolean exists;
try (ResultSet rs = statement.executeQuery("SELECT EXISTS (SELECT 1 FROM Persons)")) {
exists = rs.next() && rs.getBoolean(1);
}

java: display the elements from a database

I wrote some java code to display database, when I run the code it gives me just the last element of database , but I wanna display all elements of table
the code :
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
What should I do? Can anyone please help me to display all values?
Thank you for helping me.
I think the problem is with your code that the value of puissance is overwritten every time you get the next element. Only the last value is returned. You should put the results into a list and return the whole list:
public List<String> RecupererPuissance() {
List<String> puissances = new ArrayList<String>();
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance = rs.getString("Power");
puissances.add(puissance);
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissances;
}
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
rs.first();
int count=0;
while (rs.next()) {
System.out.println("count = "+count);
count+=1;
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
If you see count printed only 1 time :
it would mean that you have only 1 row in column Power
and you maybe referring to the wrong column in your code

Sequence.NEXTVAL in Oracle 12c with rs.getInt() or getLong() fails - so what datatype it returns?

I am fetching next value of sequence with the ps = connection.prepareStatement("select seq.nextval from dual");
But neither getLong() nor getInt() works.
So how to correctly get the value from the ResultSet then?
full code:
public static long seqGetNextValue(String sequence) {
Connection connection = Util.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
Long value = new Long(0);
try {
ps = connection.prepareStatement("select ? from dual");
ps.setString(1, sequence);
rs = ps.executeQuery();
if (rs.next()) {
value = rs.getInt(1);
}
System.out.println("Next payment Id: " + value);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Util.close(connection, rs, ps);
}
return value;
}
The exception is below, for getInt it looks the same:
java.sql.SQLException: Fail to convert to internal representation
at oracle.jdbc.driver.CharCommonAccessor.getLong(CharCommonAccessor.java:258)
at oracle.jdbc.driver.T4CVarcharAccessor.getLong(T4CVarcharAccessor.java:562)
at oracle.jdbc.driver.GeneratedStatement.getLong(GeneratedStatement.java:228)
at oracle.jdbc.driver.GeneratedScrollableResultSet.getLong(GeneratedScrollableResultSet.java:620)
at org.apache.tomcat.dbcp.dbcp.DelegatingResultSet.getLong(DelegatingResultSet.java:228)
at org.apache.tomcat.dbcp.dbcp.DelegatingResultSet.getLong(DelegatingResultSet.java:228)
at util.Util.seqGetNextValue(Util.java:85)
PreparedStatements cannot bind object names, just values. If you attempt to bind seq.nextval as you're doing above, you're actually binding the string literal 'seq.nextval', so your code is effective doing the following:
SELECT 'seq.nextval' -- Note that this is a string!
FROM dual
Now it's obvious why getInt and getLong don't work - you aren't querying a number.
TL;DR - you cannot bind a sequence's name, and should just hard-code it in the statement (or use string manipulation/concatination to create the query). Once you've done that, you can use either getInt or getLong, depending on the values you expect to get. E.g.:
try {
ps = connection.prepareStatement("select " + sequence + " from dual");
rs = ps.executeQuery();
if (rs.next()) {
value = rs.getInt(1);
}
System.out.println("Next payment Id: " + value);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Util.close(connection, rs, ps);
}

resultset isn't going into while loop and set the value

Observing a strange behavior of this piece of code,because resultset is not giving the null value(doing SOP it's clear)but not going into while loop(that is quite strange!)and it's simple dao class,it's not able to set the value in user object:
public class DAO{
public List<User> searchAllUsers(int offset ,int noOfRecords, String column, String value){
String query="select SQL_CALC_FOUND_ROWS * from info where '"+column+"' like '%"+value+"%' order by serialNo asc limit " + offset + " , " + noOfRecords;
// String query="select * from info where '"+select+"' like '%"+search+"%' order by serialNo asc";
System.out.println("1");
List<User> list = new ArrayList<User>();
User user=null;
try {
System.out.println("b4 Connection");
connection = getConnection();
System.out.println("After Connection");
stmt = connection.createStatement();
System.out.println("Create statement");
ResultSet rs=stmt.executeQuery(query);
if(rs!=null)
System.out.println("1> Hi rs:"+rs);
while(rs!= null && rs.next()){
System.out.println("hi...!!");
user=new User();
user.setSerial(rs.getInt(1));
System.out.println("Serial : "+rs.getInt(1));
user.setName(rs.getString(2));
user.setEmail(rs.getString(3));
user.setImei(rs.getString(4));
System.out.println("I'm here !");
user.setModel(rs.getString(5));
user.setManufacturer(rs.getString(6));
user.setOsversion(rs.getString(7));
user.setHdyk(rs.getString(8));
user.setDate(rs.getString(9));
user.setAppname(rs.getString(10));
list.add(user);
System.out.println("Last..");
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
System.out.println("2> :" +rs);
if(rs.next()){
this.noOfRecords = rs.getInt(1);
System.out.println("3> :" +this.noOfRecords);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
finally
{
try {
if(stmt != null)
stmt.close();
if(connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
And it corresponding output is :
1
b4 Connection
After Connection
Create statement
1> Hi rs:com.mysql.jdbc.JDBC4ResultSet#35e6e3
2> :com.mysql.jdbc.JDBC4ResultSet#c9630a
3> :0
Even I'm also using the same code like it for select All user's and that point of time I'm getting proper o/p.
Spending so many hours for it,but unable to resolve it-where I'm going wrong....so your review & comment will be always welcome.
That's because your query didn't fetch you any row. And hence rs.next() will return false, hence the execution will not go into the while loop:
while(rs!= null && rs.next())
And you don't have to check for rs != null. It won't be null. The stmt.executeQuery always returns a ResultSet. Just have rs.next() in your while:
while(rs.next())
And yes, you should use PreparedStatement for executing your query rather than Statement. Here's a tutorial which will help you get started.

get data from flat file and insert data into database in Java

I open new question about the extract data and insert to database. I change and modified the code become like this but still not working.
Flat file:
DT|00000001|TMDWH|UNIFI|00380520160|MAH SIEW YIN|11 |JALAN PP 2/8|TAMAN PUTRA PRIMA|PUCHONG|SELANGOR|47100|MALAYSIA|801110-14-5498||||||VOBB||A||11|JALAN PP 2/8|||TAMAN PUTRA PRIMA
DT|00000002|TMDWH|UNIFI|00322012091|JUNITA BINTI JAMAL|6 10 KONDOMINIUM FAJARIA|JALAN PANTAI BARU|KUALA LUMPUR|KUALA LUMPUR|WILAYAH PERSEKUTUAN|59200|MALAYSIA|800129-09-5078||||||VOBB||A|||JALAN PANTAI BARU|6|KONDOMINIUM FAJARIA|KUALA LUMPUR
Program:
public void massageData(String tmp) {
String[] fields = tmp.replace("\"", " ")
.replace("\'","\'\'")
.trim()
.split("\\s*\\|\\s*");
Connection conn = null;
ResultSet rs = null;
PreparedStatement stmt = null;
String actualMSISDN = parseMSISDN(fields[5]);
if (actualMSISDN.length() > 8) {
String [] aNo = getAreaCode(actualMSISDN).split("\\|");
field[0] = getiCtr(parseMSISDN(fields[5]));
String stateCode = lookupStateCode(State);
String sQuery = "insert into DATA_999 ( ,RecordType,RecordNumber,SourceSystemApplicationId,TargetApplicationId,TelNo,Name,HouseNo,StreetName,AppartmentSuite,TownCity,State,PostalCode,Country,NewIC,OldIC,PassportNo,BRN,LatitudeDecimal,LongitudeDecimal,ServiceType,IndicatorType,CreateDate,Filler,Cr_Nl,HouseNo_New,LotNo_New,StreetName_New,AptNo_New,BuildingName_New,LowIDRange,HighIDRange,SectionName) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try {
conn = ds.getConnection();
stmt = conn.prepareStatement(sQuery);
int col = 0;
for (String field : fields) {
stmt.setString(++col, field); // Note: SQL API is 1-based (not zero-based)
}
int dbStat = stmt.executeUpdate();
conn.close();
} catch (SQLException s){
logger.error(s.getMessage());
}
finally {
try {if (stmt != null) stmt.close();} catch (SQLException e) {}
try {if (conn != null) conn.close();} catch (SQLException e) {}
}
}
}
You're actually trying to insert double the amount of fields in 1 row. Also you seem to have an error in your sql query: the first field is absent and there's only a comma there.
It also seems to me that you're not doing anything yourself: you use the advice people give you, change your code and if it doesn't work you create a new question.

Categories

Resources