I am trying to create events using Java code with hibernate. I verified my syntax for CREATE EVENT in MySQL Workbench, and I verified my Java code with a simple UPDATE query. But when I am trying to use both it just doesn't work. I am not getting any error message, just that 0 rows were affected. My code is as follows:
String sql = "CREATE EVENT IF NOT EXISTS test_event ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 20 SECOND ON COMPLETION PRESERVE ENABLE DO UPDATE my_table SET last_error_message='my test' WHERE ID=17;";
session.beginTransaction();
SQLQuery query = session.createSQLQuery(sql);
int result = query.executeUpdate();
session.getTransaction().commit();
....
session.close();
thanks a lot
How do you know if any new events were created? You can try
show events from <SCHEME_NAME>;
This will show all the events that are registered to the given schema.try printing the session\statement warning stack...
Get jdbc connection from your session: How to get jdbc connection from hibernate session?
Use JDBC to execute DDL
...
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
// ...
} finally {
// close stmt
}
...
First, you need to make sure your database is prepared to execute an event. for that, you need to run the following command.
SHOW PROCESSLIST;
MySQL uses a special thread called event schedule thread to execute all scheduled events.
if you see your process list like the above picture. you need to run the below command to enable MySQL event execution.
SET GLOBAL event_scheduler = ON;
Then when you execute the "SHOW PROCESSLIST;" command you will see the below list which shows the specific thread for event execution in MySQL.
Now you can create your event using any MySQL client interface.
Related
I've an application created using dropwizard framework where I've registered a quartz-scheduler job scheduled to run after every specified duration. This job fires a SQL query to SQL Server DB and iterates the ResultSet and sets the data to a POJO class which is later pushed to a queue.
The SQL query has UNION joining multiple tables which fetches the data for the records modified in a delta time using the last_modified_time column of the related table in where clause. DB jar included in pom.xml is sqljdbc-4.4.0 and quartz version is 2.2.1
The query looks like this:
SELECT
u.last_modified_date,
u.account_id,
u.user_id,
ud.is_active
FROM user u WITH (NOLOCK)
JOIN user_details ud with (NOLOCK) ON u.account_id = ud.account_id AND u.user_id = ud.user_id
WHERE u.last_modifed_date > ? AND ud.last_modifed_date <= ?
UNION
SELECT
u.last_modified_date,
u.account_id,
u.user_id,
ud.is_active
FROM user u WITH (NOLOCK)
JOIN user_details ud with (NOLOCK) ON u.account_id = ud.account_id AND u.user_id = ud.user_id
JOIN user_registration_details urd WITH (NOLOCK) ON urd.account_id = u.account_id AND urd.user_id = u.user_id AND urd.reg_id = ud.reg_id
WHERE urd.last_modifed_date > ? AND urd.last_modifed_date <= ?
This query is called by simple connection statement and resultset like this
final ManagedDataSource datasource configuration.getDatabase().build(environment.metrics(), "sql");
// configuration is the configuration class in a drop wizard application and configuration.getDatabase() returns
// the DataSourceFactory with all credentials like user, password and url set into it
try (Connection conn = dataSource.getConnection()) {
int resultSetType = SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY;
int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
LOGGER.info("Starting execution: ");
try (PreparedStatement pstmt = conn.prepareStatement(getQuery(), resultSetType,resultSetConcurrency))
{
setQueryParameters(pstmt);
try (ResultSet rs = pstmt.executeQuery();)
{
//process results
}
}
} catch (SQLException | IOException ex) {
LOGGER.error(“Error occurred “ + ex);
}
LOGGER.info("Completed execution: ");
In a simple execution, it prints the logs "Starting execution" and then processes the records and prints "completed execution". But sometimes during the execution, it's printing the logs "Starting execution" and "completed execution" but this query is not actually fired to the SQL DB.
As I didn't get the records which I modified in that delta time, I put the profiler to check if the query is actually fired and didn't found this query firing to the DB. Also, I've tried adding log4jdbc library http://code.google.com/p/log4jdbc/wiki/FAQ to print the query to the logs but no logs were printed for this query.
with (NOLOCK) is not MySQL syntax. Look at the settings in the wizard and see if you have specified the correct RDBMS engine. In particular, it sounds like SQL Server syntax.
The equivalent may involve setting the TRANSACTION ISOLATION LEVEL to something like READ UNCOMMITTED.
I turned the SQL Profiler on this query and filtered it for my server to check if the query was actually hitting the DB from my application and found that the profiler could only find it rarely hitting the DB. So, I thought there might be some caching happening at mybatis level. Then I added more logs and performed debug analysis on mybatis by enabling all kind of logging and to check if there are any caching at local level or second level cache mybatis configuration but that wasn't the cause.
Then I used spy jdbc driver log4jdbc driver to log all the queries, parameters and all db information requests at db level.
My organization is using Spunk application to display logs from all the applications deployed to the different host servers. While checking the logs in splunk, I observed the same query was printed twice in the logs but when I noticed deeply it was printing one from my instance and another execution from the different instance deployed on some other server. I logged in to that server and found the same application deployed over there not updated since months. It was found to be multiple application instances running in the same environment but on two different servers and there is no way I could figure out that an application was deployed on multiple hosts.
Thank you #halfer for all the help and bounty.
I am trying to run an alter system command through JDBC which is required for me to run a query optimally.
I`m not sure if I am doing it right as I am not able to see the effect of the alter session statement. How do we persist the same session in JDBC what I mean is if I use the same connection and not close it does it mean I am using the same session?
The connection and database class are just helper classes to get a connection.
MyConnection mainDatabaseConnection = new MyConnection("jdbc:oracle:thin:#aas:111:"+tm.databaseName, "sys as sysdba", "xxx");
Database mainDatabase = new Database(mainDatabaseConnection.getConnection());
/* Fill in with data got for the main database */
//String auditQuery = mainDatabase.generateAuditQuery(tm.schemaName, tm.tableName);
String auditQuery = "select id, name, school, start, end from user where start>'11-11-11' and start<'12-12-12'";
System.out.println(auditQuery);
ResultSet rs = mainDatabase.runQuery("ALTER SESSION set optimizer_use_invisible_indexes = true");
// ResultSetMetaData md = rs.getMetaData();
// System.out.println(md.getColumnCount());
rs.close();
mainDatabase.close();
mainDatabaseConnection.close();
I am not sure if the alter session command ran successfully.
Question 2: When I run a Select query using Statement I get a resultSet. WHen I close the statement does the resultSet get closed too? So, as soon as I close the statment or connection does all the fetched data go away?
A java.sql.Connection object represents a session in Oracle. As long as you keep using the same object, you're in the same session.
With regard to closing Statements, as Mark Rotteveel commented - closing a Statement will indeed close a ResultSet that was opened by it. It would, however, be recommended to close the RestulSet once you're done with it, even (or, actually - especially) if you intend to reuse the Statement object.
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!
I have java code that connects to a remote oracle 11g EE db server. If i run a particular query in sqlplus it returns one result
SQL> SELECT COURSENAME from COURSES where skillID=1;
COURSENAME
--------------------
basic
But if I run the same query from the java code below it returns no results. I can copy the query syntax out of the query variable in the java debugger and running it on oracle so I know there is no syntax issue with the query. Also, it is not SQL exceptions or class not found exceptions so it seems to be running the query successfully -- just returning zero results.
What might be going on?
private String getCourseForSkill(int skillID){
try{
Class.forName("oracle.jdbc.OracleDriver");
String query="SELECT COURSENAME from COURSES where skillID=" + skillID ;
con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
rs = stmt.executeQuery(query);
rs.next();
return rs.getString("COURSENAME");
}
catch (ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return null;
}
I think you're connecting to different Oracle instances, or more likely, as different Oracle users in the two cases
#GreyBeardedGeek the URL looks like "jdbc:oracle:thin:#website:port:orcl I get to the manual query by doing ssh#website, authenticating and then running command=sqlplus
Safer to run sqlplus <username>/<password>#<orainstancename>, because you can explicitly specify the oracle instance ID. In your case, it seems your program is using jdbc connection jdbc:oracle:thin:#website:port:orcl, so your orainstancename would be 'orcl' - just ensure that your tnsnames.ora file has the instance 'orcl' with the same 'port' as used by the jdbc connection
How to debug a little more
Run the following code:
con = DriverManager.getConnection(url, user, password);
con.setAutoCommit(false);
String insert="INSERT INTO COURSES (SKILLID, COURSE)"+ // can add other columns
"values (?, ?) );" // add ? for other columns
PreparedStatement ps = con.createPreparedStatement();
ps.setInt(1, 999);
ps.setString(2, "Complete Bullwarks");
// can set other columns
ps.executeUpdate(insert);
con.commit();
NOW connect manually, re-run your original select statement & see if the added row is there. If no error in java and no new row in Oracle: extremely likely you're using 2 different Oracle instances/schemas.
ALSO rerun your original java select code, but with SkillID=999 - extremely likely it will work.
Cheers
I had to do a commit to add the rows. When I typed commit; into the sql plus terminal then the remote jdbc connection could 'see' the rows. I am used to SQL server where you don't have to explicitly do these kinds of commits when using linq-to-sql or sql management studio.
It can be three issues.
1) skillID <> 1 in your Java code. Add debug and check.
2a) You are connecting to another database.
2b) You are connecting to the same database but SELECTING from a table in another schema.
To check 2a and 2b:
select user from dual; -- connect username
select name from v$database; -- database name
select host_name from v$instance; -- host name database is running on
This query returns all three into one result.
select user || '' || d.name || '' || i.host_name
from v$database d, v$instance i;
Assuming you are actually connecting to the same database this is caused by not committing the INSERT in the sql*plus connection.
Oracle by default does not run in auto-commit mode when connecting via OCI (which sql*plus uses to connect). Any DML(INSERT ...) executed in sql*plus will not be visible to any other session until it is committed. This is because Oracle provides a read committed isolation level by default. The only thing visible to other users across sessions are write locks.
It doesn't matter if you connect the second connection via JDBC or OCI, it won't see the changes till you commit the first connection.
To test this out try opening 2 sql*plus connections and run the following:
-- Executing DDL in Oracle causes an implicit commit before and after the
-- command so the second connection will see the existence of this table:
CREATE TABLE foobar ( x VARCHAR(1) );
Execute this in connection #1 - you should get zero (we haven't inserted anything yet):
SELECT COUNT(*) FROM foobar;
Execute this in connection #2:
INSERT INTO foobar ( x ) VALUES ( 'A' );
Execute this in connection #1 - you should still get zero (INSERT is not committed so connection #1 cannot see it):
SELECT COUNT(*) FROM foobar;
Execute this in connection #2:
COMMIT;
Execute this in connection #1 - you should get 1 (it's committed now):
SELECT COUNT(*) FROM foobar;
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.