Oracle - Available data not visible in SQL Command Line/Java Program - java

I am creating a basic java application with Oracle database. I use Oracle SQL Developer to interact with oracle database.
I created tables and inserted data using Oracle SQL Developer and all operations were successful.But when I try to get those records in the java program, it does not get any results.
I debugged the java program and found out the issue is the resultset not getting any records from DB.(Other things are fine)
try {
stmt = dbConnector().createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString("AGE"));
}
} catch (SQLException e) {
e.printStackTrace();
Because of that, I tried to verify using SQL command line and it did not show the entries I entered using SQL developer. I cannot figure out what is wrong. Please refer the attached.
A help regarding this is much appreciated.

Please make sure that you have commit the transactions done in Oracle SQL Developer. Most probably that may be the reason for not showing records both in SQL plus & your java program.
You may commit by clicking on the commit button on Oracle SQL Developer toolbar (i.e. 6th button from left)

Related

Error or wrong type of code while creating connection & execute SQL query statements using mysql in java

I'm using MySQL 5.7 with Java in Eclipse, and the connection statement below code below is causing an error when I try to connect:
try
{
//1. Get a connection to database
jdbc:mysql://localhost:3306/databaseName?autoReconnect=true;useSSL=false;
// 2. Create a statement
Statement myStmt=myConn.createStatement();
// 3. Execute SQL query
ResultSet myRs=myStmt.executeQuery("select * from employee");
//4. Process the result set
while(myRs.next())
{
System.out.println(myRs.getString("last_name")+","+myRs.getString("first_name"));
}
}
catch(Exception exc){
exc.printStackTrace();
}
First things first.
Code will only be used to validate the error. So you must paste the error fired by your program.
Since we don't have enough information to the problem, I will just cover basic troubleshooting.
Basic trouble shooting:
Do you have the driver? if not, you can download it here.
Next, Do you have the driver on your project class path? If not yet, you must add it. see how here
Did you load the driver to the program? if not, Class.forName("com.mysql.jdbc.Driver"); // Load Driver like that before doing anything.
Did you establish the connection? if not, Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/DATABASE","USERNAME","PASSWORD");//3306 or port number depends on you config, same with DATABASE, USERNAME, PASSWORD
After the connection were established, so you should create a statement object like Statement s = con.createStatement(); // Create Statement. This will be used to execute sql commands.
finally, you can execute the commands like s.execute("select * from employee"); // Execute Query NOTE that s here is the variable created on number 5.
If all of the above were properly done but still gets an error, check if your have the database server running. In you case, mysql. Make sure there were not other installation of mysql prior to your current mysql. Sometimes, it will mess up your database. Troubleshooting your mysql, see mysql official doc here
While possible error is the datatype of mysql to your java code or getting a column that does not exist on your query or worse the column does not exist on your table.
Hope that help you and other who needs it.

Java mysql AWS execute succeed and then select does not return the new value

I am working with AWS RDS (specifically mysql) and I am using SQL Workbench/J as a GUI tool. My server side code written in Java and here is my code:
Insert code:
try {
Statement myStatement = insertConnectionObject.createStatement();
myStatement.executeUpdate("INSERT INTO friends VALUES('buddy', '15', '123');");
myStatement.close();
} catch(Exception ex) {
// code for handling exceptions
} finally {
myStatement.close();
insertConnectionObject.close();
}
After that, I call the select code from the same table:
try {
Statement myStatement = selectConnectionObject.createStatement();
ResultSet returnedFriends = myStatement.executeQuery("SELECT * FROM friends;");
//unfortunately, the returnedFriends will not return the new inserted value 'buddy'
} catch(Exception ex) {
// code for handling exceptions
} finally {
myStatement.close();
insertConnectionObject.
unfortunately, the returnedFriends will not return the new inserted value 'buddy'.
If I will click the 'commit any pending database changes' button in the SQL Workbench/J GUI tool, and then run the select statement, the new value 'buddy' will return.
What have I tried until now?
Use the same connection object for both insert and select.
Open and close the connection after the insert command, and after every select command.
disable the auto commit and try to commit manually.
Inserting via code, and then selecting directly from the DB.
Have you tried setAutoCommit(true) on the connection, just in case it isn't?
Also, if your select is just to get a new key don't forget you can call myStatement.getGeneratedKeys() in with the update.
You should use executeQuery() to select . executeUpdate() returns nothing but int. It should give a compile time error, are you sure that the code is compiling rather than running last working version?
executeUpdate(String sql) Executes the given SQL statement, which may
be an INSERT, UPDATE, or DELETE statement or an SQL statement that
returns nothing, such as an SQL DDL statement.
So change your select code as below:
ResultSet returnedFriends = myStatement.executeQuery("SELECT * FROM friends;");
My problem was as simple and annoying as can be - apparently, I had to close the Workbench GUI when working from the code, which is kind of wired and requires probably deeper investigation from the Workbench / AWS teams.
Anyways, after closing this interface, everything just worked.
Thanks for the help!

Connecting to Oracle with JDBC causes queries to return zero rows.

So I have been playing around with querying databases using the standard
Statement s = connection.createStatement();
ResultSet rs = s.executQuery(queryString);
ResultSetMetadata rsmd = rs.getMetaData();
while(rs.next)){
String code = "";
String value = "";
for(int i = 1; i <= rsmd.getColumnCount(); i++){
Object obj = rs.getObject(i);
if(i == 1){
code = obj.toString():
}
else{
label = obj.toString();
}
}
//Store code and labels in map
}
...go on to close statement and move on.
I am trying to select two columns from a table in each instance.
For the most part this works well. When working with MySql & Microsoft Sql databases I get a result set full of data in the table. However when I try to do this with an Oracle database I get an empty result set.
I have tested my query string in the SQL Developer application and it works fine, returns my data. But the result set doesnt contain anything. The resultSet metadata says that it has two columns though. Is there anything I need to do when interacting with an Oracle Database that is different from the other two? Thanks.
If your query works when you run it against the Oracle database, and you know the code works since you've run it against MySQL, then some other things to try are:
1.) Make sure your JDBC connection URL is correct. Are you sure you are connecting to the database that you intend to? (i.e. - the one that would return the rows you expect?)
2.) Take into account credentials. Make sure you are using the same credentials through JDBC that you are when connecting to Oracle directly.
3.) Make sure both connections are being made from the same machine and with the same environment. Oracle drivers rely on environment variables to find a file (I believe it is called tnsnames.ora, or something like that) that contains the alias & connection info. Getting different versions of that file could point you to different Oracle instances.
4.) Try manually specifying your schema name in the query. So instead of select * from my_table use select * from my_schema.my_table. Sometimes Oracle clients will configure their sessions to have default schemas set up in their preferences.
5.) If your are attempting to select data that you've inserted with your Oracle client, make sure you've committed the transaction in your Oracle client so that the data is visible to other sessions.
One last debugging tool to use is to try connecting via the Squirrel DB client. Squirrel is a 100% pure java SQL client that connects to any DB using JDBC. It would be a good test to make sure your JDBC Driver, Connection URL, etc. are all valid.
The database table has records but the JDBC client can't retrieve the records. Means the JDBC client doesn't have the select privileges. Please run the below query on command line:
grant all on emp to hr;

Poor Google Cloud SQL performance

I'm having a hard time getting decent performances with Google Cloud SQL, I'm doing some pretty basic CRUD operations, for instance:
public BaseUser getUser(String token) throws SQLException{
Connection conn = DriverManager.getConnection(JDBC_CON_STRING);
PreparedStatement ps = conn.prepareStatement(GET_USER_BY_TOKEN_QUERY);
ps.setString(1, token);
ResultSet rs = ps.executeQuery();
List<BaseUser> users = inflateUser(rs);
if(users.size() == 0){
return null;
}
if(users.size() > 1){
logger.info("DATABASE MAY BE CORRUPTED, THERE'S MORE THAN 1 USER WITH THE SAME TOKEN");
}
ps.close();
rs.close();
conn.close();
return users.get(0);
}
And getting an average of 450ms reponse time for each query. += 150 for openConnection, 150 for operation, 150 for close. See the img. below.
I've read the google documentation, forums and multiple blogs and still can't see what I'm doing wrong (I must be doing something wrong, 450ms/query is wayyy to much...)
UPDATE 1: I'ts definitively a Google Cloud SQL issue, I installed my own local MySQL server and I'm having way better performances (80ms for an "insert or update", then select finally commit.), hope I could get some hints from Google dev. team, I really like the whole Google cloud platform, but it's simply impossible to work with that level of latency =(
UPDATE 2: 2014/05/06 The latency problem is the same with a D0 or a D16. Trying to insert 10000 rows (3 varchar and a ~100bytes blob) takes 32s from a Google ComputeEngine VM because of the latency. The duration is the same with 10000 inserts and a single batch insert. If I use 64 threads, then the duration is down to 3s. I tested with the native mysql jdbc driver.
Any suggestions?
Thanks!
Give it a try with the MySQL Connector/J driver in AppEngine, it may give better performance.
See https://developers.google.com/appengine/docs/java/cloud-sql/#Java_Connect_to_your_database for the classname and URL format to use.
Rob
I had problem with GAE + cloud SQL used with php and the socket.
The problem was my query that used actually 3 queries and read thousands of rows even tough only outputtet couple.
I found it with HeidiSQL and putting EXPLAIN in front of the select query.
Had to make the join in php side so that the load time (inspected in chrome devtools, not mysql run time) of that query-set dropped from 600 ms to 151 ms

How to view Execution Plans for Oracle Database in Java

With SQL Plus for Oracle Database, I can call
SET autotrace on
and then see Execution Plan, statistics, etc.
The problem is that I want access to information about the Execution Plan and statistics in my Java program. I typically have done something like this to execute a sql statement,
Connection connection = //INITIALIZE HERE;
Statement getColumn = connection.createStatement();
ResultSet results = getColumn.executeQuery("INSERT SQL QUERY HERE");
while(results.next())
{
//view results
}
Is there a way I can get the Execution Plan and Statistics? Thanks.
You can query the V$SQL_PLAN table to get the explain plain. Alternatively you can query the PLAN_TABLE, you can see more details on this HERE.

Categories

Resources