Not getting result from Cloud SQL in Android after successful query execution - java

I am trying to connect to Cloud SQL. Queries are executing successfully but I am not getting results. I created database and tables using executeQuery() and it executed successfully but executeQuery() returned false.
Here is my code -
Connection connection;
String query = "SELECT NOW()";
System.out.println("Connecting...");
try {
//Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://<IP address>/test", "root", "root");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
String result = "No Result Found";
if (resultSet.isFirst())
result = resultSet.getString(0);
System.out.println("Result - " + result);
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Process Terminated.");

Looks like you have tried to fetch data from ResultSet from index 0
i.e., result = resultSet.getString(0); which is not correct.
ResultSet's index starts with '1' instead of zero.
Try out with:result = resultSet.getString(1);
For reference: https://www.javamex.com/tutorials/database/jdbc_result_set.shtml#.Wv1PpnWFPPY

Related

How to switch between multiple result sets in Sybase using JDBC

I have some code to test the migration of a sybase database into a SQL Server one. A part of the testing is to execute stored procedures in both databases and compare the results.
I have a stored procedure that returns 10+ result sets. The issue is that with Sybase, when I try to switch from one result set to the other, it fails. The 2nd result set ends up being null which means I'm only getting result set back in Sybase. This code works for SQL server.
Any idea how to get this to work for Sybase?
I'm using java 8 and JConn 4.
public static void storedProc(){
String strConnectionString = "jdbc:sybase:Tds:host:port?";
String strUsername = "username";
String strPassword = "pass";
String strQuery = "exec storedprocedure";
Connection connection = JDBCUtils.databaseConnection(strConnectionString, strUsername, strPassword);
PreparedStatement preparedStatement = connection.prepareStatement(strQuery, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int intResulSet = 0;
int count = 0;
try{
preparedStatement.executeQuery();
ResultSet resultSet = preparedStatement.getResultSet();
while (resultSet!=null) {
intResulSet +=1;
System.out.println(resultSet);
System.out.println("Result Set: " + intResulSet);
if (!resultSet.next()) {
System.out.println("Result Set is Empty");
} else {
do {
count+=1;
System.out.println(count);
} while (resultSet.next());
}
preparedStatement.getMoreResults(Statement.CLOSE_CURRENT_RESULT);;
resultSet = preparedStatement.getResultSet();
System.out.println(resultSet);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
connection.close();
}
This is just a piece of my code. Not doing any of the comparisons here. This is just trying to successfully switch from one resultset to the next.
This same exact code switches through and prints results for all the result sets in SQL, but unfortunately, no luck in Sybase.
I've also tried to use callable statement instead of prepared statement and same issue.

Sql code give invalid SQL statement in Java but it works in SqlDeveloper

I tried to make crud , but insert statement do not work from code
try {
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
conn2 = DriverManager.getConnection(dbURL2, username, password);
String sql="INSERT INTO Produce(name,description,Produce_Date,Price,CATEGORY_ID,Person_ID)VALUES('"+name+"','"+description+"',TO_DATE('"+sqlDate+"', 'yyyy-mm-dd'),"+price+","+category_Id+","+person_id+")";
System.out.println(sql);
stmt = conn2.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
if (conn2 != null && !conn2.isClosed()) {
conn2.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
I made a System.out.println to see my sql and to execute it to understand where is the problem, this is my String, and it works in sqlDeveloper:
INSERT INTO Produce(name,description,Produce_Date,Price,CATEGORY_ID,Person_ID)VALUES('ew','rrr',TO_DATE('2018-11-14', 'yyyy-mm-dd'),12.0,2,2)
you are using insert SQL query to retrieve result.
I believe to retrieve name you need to execute select statement

Not able to get count using JDBC connection

I'm not able to get the number of rows by making a query. I've used JDBC connection for it. But, rather it doesn't show any error, but it stops executing the process.
Here is my code
Transaction transaction=null;
Connection c = null;
Statement stmt = null;
ResultSet result;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(
"jdbc:postgresql://192.168.1.7:5432/"+userDB,
"postgres", "openerp");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
int count = 0;
try {
LOGGER.info("In try of get");
factory = HibernateUtil.connectDB(userDB);
LOGGER.info("Connected to DB");
//Open Session
session = factory.openSession();
//Begin Transaction
transaction = session.beginTransaction();
LOGGER.info("Beginning the transaction");
stmt = c.createStatement();
String sql = "SELECT COUNT(*) FROM mycontent_messages where status = '0'";
count = stmt.executeUpdate(sql);
LOGGER.info("successfully got count : "+count);
c.commit();
stmt.close();
c.close();
Exception which I'm getting is
org.postgresql.util.PSQLException: A result was returned when none was expected.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:307)
at net.vsspl.mycontent.daoimpl.contentImpl.getUnreadCount(contentImpl.java:379)
at net.vsspl.mycontent.services.countUnreadMessages.main(countUnreadMessages.java:49)
It logs upto "Beginning the transaction". After that it doesn't show anything. Is there any issue in my code?
You want to get the result set from the query and process it that way, not get the number of affected rows..
ResultSet rs = stmt.executeQuery(sql);
int count = 0;
if(rs.next())
{
count = rs.getInt(1);
}
count = stmt.executeUpdate(sql);
You're not executing an update; you're executing a query.
here you are executing a query to fetch the count of the records so you should be using
resultSet = stmt.executeQuery(sql);

Java and SQLite: Throwing ResultSet closed but proceeding

I've got a following problem: I'm trying to insert data (in this case a username) into a table using the following code:
void AddNewUser(String name, Connection conn){
if(ret == null){
ret = new DB_Retriever(conn);
}
if(!ret.UserExists(name, conn)){
try{
Statement stm = conn.createStatement();
stm.executeUpdate(DB_OperationalData.insert_new_user[0][0] + name + DB_OperationalData.insert_new_user[0][1]);
stm.executeUpdate(DB_OperationalData.insert_new_user[1][0] + name + DB_OperationalData.insert_new_user[1][1]);
stm.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
By the way: It absolutely doesn't matter what I put in the catch clause, nothing that I put there is executed. Just to make everything clear, here is the content of the DB_OperationalData.insert_new_user String array:
public static final String[][] insert_new_user = {
{"INSERT INTO User (Username, Status) VALUES ('","','IN');"},
{"INSERT INTO Statistics (Player_ID) SELECT ID FROM User WHERE Username='","';"}};
The second statement is supposed to copy the ID of the user that is inserted and put it into Player_ID field of the Statistics table (Table User's ID is an autonumbered field).
The exception I get is:
Error while processing the query: java.sql.SQLException: ResultSet closed
What is interesting, is that it works and the data is added correctly but I simply do not want any exceptions thrown.
That's the console output I get:
This is 'data' Package Testing class
Connection to the database established.
The number of tables existing in the database is: 0
All the queries have been processed successfully
Adding new users:
Error while processing the query: java.sql.SQLException: ResultSet closed
All the lines above the Exception are my own printouts, so I know what has actually happened.
[EDIT]
I have changed the code to use the PreparedStatement instead of ordinary Statement and the current try clause looks as follows:
PreparedStatement pstm = conn.prepareStatement(DB_OperationalData.insert_new_user[0]);
pstm.setString(1, name);
pstm.addBatch();
conn.setAutoCommit(false);
pstm.executeBatch();
conn.setAutoCommit(true);
pstm.close();
And the output is (still regardless of the contents of the catch clause):
This is 'data' Package Testing class
Connection to the database established.
The number of tables existing in the database is: 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at org.sqlite.PrepStmt.batch(PrepStmt.java:173)
at org.sqlite.PrepStmt.setString(PrepStmt.java:254)
at data.DB_Writer.AddNewUser(DB_Writer.java:28)
at data.DataHandler.AddNewUser(DataHandler.java:94)
at data.Tester.main(Tester.java:18)
All the queries have been processed successfully
Adding new users:
Error while processing the query: java.sql.SQLException: ResultSet closed
[EDIT 2]
With regards to the original version, when I remove the stm.close(); there is absolutely no difference and I still get the 'ResultSet closed' Exception.
[EDIT 3]
Here is the code of the method that is calling the above:
public void AddNewUser(String username)throws IllegalUsernameException{
if(username.length()==0 || username.length()>20){
throw new IllegalUsernameException();
}
writer.AddNewUser(username, conn);
}
The connection to the database is established by this class:
class DB_Connection {
public static Connection getConnection(){
Connection conn = null;
try{
Class.forName("org.sqlite.JDBC");
}
catch(ClassNotFoundException e){
log("Error while loading the database driver: " + e);
return null;
}
try{
conn = DriverManager.getConnection("jdbc:sqlite:database.db");
}
catch(SQLException e){
log("Unable to connect to the database: " + e);
return null;
}
return conn;
}
public static void log(String msg){
System.out.println(msg);
}
}
The DB_Retriever's method that is checking for the existing username:
boolean UserExists(String name, Connection conn){
String result = "";
try{
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(DB_OperationalData.user_exists[0] + name + DB_OperationalData.user_exists[1]);
result = rs.getString("Username");
}
catch(SQLException e){
System.out.println("Error while processing the query: " + e);
}
if(result.equals(name)){
return true;
}
return false;
}
The only location where Error while processing the query: java.sql.SQLException: ResultSet closed could be printed to the console is in UserExists(..), unless there is another method with a similar catch block. Indeed the ResultSet is not used correctly in UserExists, what may cause the error.
For a more complete description of how to work with JDBC look at this answer or the JDBC documentation. A possible alternative to the existing UserExists is:
boolean userExists(String name, Connection conn) {
PreparedStatement stmt = null;
try{
stmt = conn.prepareStatement("SELECT COUNT(Username) FROM User WHERE Username = ?");
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
rs.next(); // set cursor to first row
int count = rs.getInt(1);
rs.close();
return count > 0;
} catch(SQLException e) {
// propagate error
throw new RuntimeException(e);
} finally {
// clean up resources
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ignore) {
log("error on sql clean up", ignore);
}
}
}
}

jdbc - sql server not showing any output / error in the console

I am trying to connect to sql server 2005 from my Java application using
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionurl = "jdbc:sqlserver://servername\\SQLEXPRESS;" + "database=master";
Connection con = DriverManager.getConnection(connectionurl);
System.out.println("Connected to SQL Server");
String sql = "select * from employee";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString(1) + " " + rs.getString(2));
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
On executing it, I do not get any output / error at the console. What am I missing?
Maybe there is no records in the table employee.
Or it throws an Exception whose e.getMessage() returns ""(I don't think so,but to avoid it,You can use e.printStackTrace() instead).
actually,the correct answer is...
when you insert the record in sql prompt we have to commit that record by command commit;
sql>commit;
even thought when you insert the record after that you can check by command select *from table;
record is inserted successfully...record is there
but in command prompt when we executing java program records are not displaying....
so commit the record when u inserted..
thankyou

Categories