Not Able to give previleges...Openoffice error - java

This is the code i had written to save the data into the openoffice database.
but its giving error.i m not understanding y it is appearing.
package coop.data;
import java.sql.*;
/**
*
* #author spk
*/
public class Connectionsetting {
private static Connection con;
private static Statement sm;
private static ResultSet rs;
public static void close()
{
try
{
sm.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void connection() {
String db_file_name_prefix = "/home/spk/Desktop/CooperHr/mydb.odb";
/*
If required change the file name if you are working in windows os
connection is in work
*/
try {
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Found");
con=DriverManager.getConnection("jdbc:hsqldb:file"+db_file_name_prefix,"sa", "");
System.out.println("Connection Eshtablished");
// con.setAutoCommit(false);
sm=con.createStatement();
// sm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int executeupdate(String query) {
//Execute & update block insert, update, delete statements
int bool = 0;
try {
bool=sm.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
public ResultSet executeQuery(String query) {
//Block Returns single resultset,,,sql statements such as sql select
ResultSet rs=null;
try {
rs = sm.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
public boolean checkTableStatus(String tblName) {
String sql = "selec * from cat";
ResultSet rs=null;
boolean status = false;
int i = 0;
String allTableNames[] = new String[20];
try {
connection();
rs = sm.executeQuery(sql);
while (rs.next()) {
allTableNames[i] = rs.getString(0);
i++;
if (allTableNames[i].equals(tblName)) {
status = true;
break;
} else {
status = false;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
public static void main(String []args)
{
String query,s1,s2,s3,s4,s5,s6,s7,s8;
Connectionsetting cn=new Connectionsetting();
cn.connection();
s1="same";
s2="sam";
s3="923847";
s4="sam";
s5="sam";
s6="sam";
s7="sam";
s8="R01";
query="insert into Agency_Master values("+s1+","+s2+","+s3+","+s4+","+s5+","+s6+","+s7+","+s8+")";
cn.executeupdate(query);
}
}
This is the error..I m getting it when i trying to save the data into the database
Can any one plz tell me where i m wrong.
Thank you.
run:
Driver Found
Connection Eshtablished
java.sql.SQLException: user lacks privilege or object not found: AGENCY_MASTER
at org.hsqldb.jdbc.Util.sqlException(Util.java:200)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(JDBCStatement.java:1805)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(JDBCStatement.java:205)
at coop.data.Connectionsetting.executeupdate(Connectionsetting.java:52)
at coop.data.Connectionsetting.main(Connectionsetting.java:116)
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: AGENCY_MASTER
at org.hsqldb.Error.error(Error.java:76)
at org.hsqldb.SchemaManager.getTable(SchemaManager.java:510)
at org.hsqldb.ParserDQL.readTableName(ParserDQL.java:4367)
at org.hsqldb.ParserDML.compileInsertStatement(ParserDML.java:64)
at org.hsqldb.ParserCommand.compilePart(ParserCommand.java:132)
at org.hsqldb.ParserCommand.compileStatements(ParserCommand.java:83)
at org.hsqldb.Session.executeDirectStatement(Session.java:1037)
at org.hsqldb.Session.execute(Session.java:865)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(JDBCStatement.java:1797)
... 3 more
BUILD SUCCESSFUL (total time: 0 seconds)

Your connection URL looks iffy... try changing:
con=DriverManager.getConnection("jdbc:hsqldb:file"+db_file_name_prefix,"sa", "");
to
con=DriverManager.getConnection("jdbc:hsqldb:file:"+db_file_name_prefix+";ifexists=true","sa", "");
(adding a colon after "file", and appending the ifexists=true flag, as indicated by: http://hsqldb.org/doc/guide/ch04.html

It looks to me like the AGENCY_MASTER table doesn't exist. You're trying to execute an update statement, and it looks like HSQLDB can't find the AGENCY_MASTER table.
You can check whether the table exists with HSQLDB's built-in client/viewer:
java -cp hsqldb.jar org.hsqldb.util.DatabaseManagerSwing

Related

SQLException: ResultSet closed

I'm trying to execute method which should create a new object with fields from database, and everytime i run this code im getting SQLException: ResultSet closed.
public DatabasedClient getDatabaseClient(int clientDatabaseid){
if(DatabaseClientUtil.isInDatabase(clientDatabaseid)){
return DatabaseClientUtil.getDBClient(clientDatabaseid);
}else{
try{
System.out.println("Trying to find user in db");
ResultSet rs = fbot.getStorage().query("select * from database_name where clientDBId = " + clientDatabaseid);
System.out.println("deb " + rs.getString("nick"));
while (rs.next()) {
DatabasedClient databasedClient = new DatabasedClient(clientDatabaseid);
databasedClient.setUid(rs.getString("uid"));
databasedClient.setNick(rs.getString("nick"));
databasedClient.setLastConnect(rs.getLong("lastConnected"));
databasedClient.setLastDisconnect(rs.getLong("lastDisconnect"));
databasedClient.setTimeSpent(rs.getLong("timeSpent"));
databasedClient.setLongestConnection(rs.getLong("longestConnection"));
return databasedClient;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
}
Im using hikari, here are methods from AbstractStorage class
#Override
public void execute(String query) throws SQLException {
try (Connection connection = getConnection()){
connection.prepareStatement(query).executeUpdate();
}
}
#Override
public ResultSet query(String query) throws SQLException {
try (Connection connection = getConnection()) {
return connection.prepareStatement(query).executeQuery();
}
}
Screenshot from error
I hope someone will help me with this.
I think the exact error you are seeing is being caused by the following line of code:
System.out.println("deb " + rs.getString("nick"));
You are trying to access the result set before you advance the cursor to the first record. Also, your method getDatabaseClient is returning a single object which conceptually maps to a single expected record from the query. Hence, iterating once over the result set would seem to make sense. Taking all this into consideration, we can try the following:
try {
System.out.println("Trying to find user in db");
ResultSet rs = fbot.getStorage().query("select * from database_name where clientDBId = " + clientDatabaseid);
// do not access the result set here
if (rs.next()) {
DatabasedClient databasedClient = new DatabasedClient(clientDatabaseid);
databasedClient.setUid(rs.getString("uid"));
databasedClient.setNick(rs.getString("nick"));
databasedClient.setLastConnect(rs.getLong("lastConnected"));
databasedClient.setLastDisconnect(rs.getLong("lastDisconnect"));
databasedClient.setTimeSpent(rs.getLong("timeSpent"));
databasedClient.setLongestConnection(rs.getLong("longestConnection"));
return databasedClient;
}
} catch (SQLException e) {
e.printStackTrace();
}

Opening and closing database

I'm working on an application that records do my MySql database on my server. Every time I want to use the database, get the existing connection, if not, I think for the first time. When I do an insert or select, works very well, but followed that consultation, when it ends, I can never regain the connection and do not return to consultations.
My class of Database
public class Database {
/**
* Gets just one instance of the class
* Connects on construct
* #returns connection
*/
private Connection _conn = null;
private long timer;
//singleton code
private static Database DatabaseObject;
private Database() {}
public static Database connect() {
if (DatabaseObject == null)
DatabaseObject = new Database();
return DatabaseObject._connect();
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
//end singleton code
/**
* Connects with the defined parameters on Config
* Prevents re-connection if object was already connected
* #throws SQLException
*/
private Database _connect() {
try {
if (this._conn == null || !this._conn.isValid(0)) {
try {
Class.forName("com.mysql.jdbc.Driver");
Properties connProps = new Properties();
connProps.put("user", Config.Config.DB_USER);
connProps.put("password", Config.Config.DB_PASS);
this._conn = DriverManager.
getConnection("jdbc:" + Config.Config.DB_DBMS + "://" + Config.Config.DB_HOST + ":"
+ Config.Config.DB_PORT + "/" + Config.Config.DB_NAME, Config.Config.DB_USER, Config.Config.DB_PASS);
timer = System.currentTimeMillis();
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Could not connect to DB");
e.printStackTrace();
}
} else {
try {
long tmp = System.currentTimeMillis() - timer;
if (tmp > 1200000) { //3600000 one hour ; 1200000 twenty minutes
System.out.println("Forcing reconnection ("+tmp+" milliseconds passed since last connection)");
this.close();
this._connect();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Forcing reconnection");
this._conn = null;
this._connect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
/**
* Closes connections
* This has to be invoked when database connection is no longer needed
* #throws SQLException
*/
public void close() throws SQLException {
if (this._conn != null) {
this._conn.close();
this._conn = null;
}
}
/**
* Getter for connection
* #return
*/
public Connection get() {
return this._conn;
}
}
The following function I make a query:
private Statement sment = null;
private PreparedStatement psment = null;
private ResultSet rset = null;
public boolean existsByNameAndUserId(String md5, int userId, int eventId) {
Connection conn = Database.connect().get();
try {
psment = conn.prepareStatement("SELECT * FROM files "
+ "WHERE user_id = ? AND md5 = ? AND evento_id = ?");
psment.setInt(1, userId);
psment.setString(2, md5);
psment.setInt(3, eventId);
rset = psment.executeQuery();
if (rset.next()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void close() {
try { if (rset != null) rset.close(); } catch (Exception e) {System.out.println(e.getMessage());};
try { if (psment != null) psment.close(); } catch (Exception e) {System.out.println(e.getMessage());};
try { if (sment != null) sment.close(); } catch (Exception e) {System.out.println(e.getMessage());};
}
And in the next, I call the above function to find out whether or not a record with these characteristics, if not, I do an insert.
String SQL_INSERT = "INSERT INTO files (evento_id, user_id, path, thumb, preview, width, height, md5, numero_corredor, created, modified) "
+ "VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW())";
public void save(List<components.File.Schema> files) throws SQLException {
try (
Connection conn = Database.connect().get();
PreparedStatement statement = conn.prepareStatement(SQL_INSERT);
) {
int i = 0;
for (components.File.Schema file : files) {
if(!existsByNameAndUserId(file.getMd5(), file.getUserId(), file.getEventId())){
statement.setInt(1, file.getEventId());
statement.setInt(2, file.getUserId());
statement.setString(3, file.getPath());
statement.setString(4, file.getPreview());
statement.setString(5, file.getThumb());
statement.setInt(6, file.getWidth());
statement.setInt(7, file.getHeight());
statement.setString(8, file.getMd5());
statement.setString(9, null);
statement.addBatch();
i++;
if (i % 1000 == 0 || i == files.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
}
Your issue is due to the fact that you put Connection conn = Database.connect().get() in a try-with-resources statement which is what you are supposed to do but it closes your connection and when you call it again as the method _connect() doesn't have a valid test, it doesn't create a new connection. The valid test is this._conn == null || !this._conn.isValid(0), indeed in your original test you call this._conn.isValid(0) which will returns false in our context since the connection is closed so it won't create a new connection which is not what we want here.
Response Update: The second part of the problem is the fact that in the save method you call existsByNameAndUserId which closes the current connection, you should only close the statement and let the method save close the connection.

DB2 and Java. Adding data to database through GUI.

First I create a search function in my program and I implemented the same logic in adding data into the database but the search function works and the add function didn't (SQLException). I created a table from DB2 named Names with only one column FullName. Do you still need to create a new query to add data into the table? or not? I want to add data into the database through GUI.
Here is my Java Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class ConnectAndSearchDB extends JFrame implements ActionListener
{
private JTextField fieldSearch,fieldAdd;
private JButton searchB,addB;
private Connection connection;
private String name;
private ResultSet rs,rs1;
public ConnectAndSearchDB() throws SQLException,ClassNotFoundException
{
setLocationRelativeTo(null);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,2));
fieldSearch = new JTextField(20);
searchB = new JButton("Search");
fieldAdd = new JTextField(20);
addB = new JButton("Add");
add(searchB);
add(fieldSearch);
add(addB);
add(fieldAdd);
searchB.addActionListener(this);
addB.addActionListener(this);
establishConnection();
pack();
setResizable(false);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Object act = e.getSource();
if(act.equals(searchB))
{
name = fieldSearch.getText();
searchData();
}else if(act.equals(addB))
{
try {
addData();
} catch (ClassNotFoundException e1)
{
e1.printStackTrace();
System.out.println("ClassNotFound");
} catch (SQLException e1)
{
e1.printStackTrace();
System.out.println("SQLError");
}
}
}
public void establishConnection() throws SQLException , ClassNotFoundException
{
Class.forName("com.ibm.db2.jcc.DB2Driver");
connection = DriverManager.getConnection("jdbc:db2://localhost:50000/COLINN", "Colinn","ezioauditore");
}
private void searchData()
{
try
{
PreparedStatement s = null;
String query;
query = "SELECT * from NAMES";
s=connection.prepareStatement(query);
rs = s.executeQuery();
boolean matchfound = false;
while(rs.next())
{
if(rs.getString(1).equals(name))
{
matchfound = true;
System.out.println("The name "+name+" is found in the Database");
break;
}
}
if(matchfound == false)
{
System.out.println("Match Not Found");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public void addData() throws ClassNotFoundException,SQLException
{
PreparedStatement ps = null;
String query;
query = "INSERT INTO NAMES VALUES('"+fieldAdd.getText()+"')";
ps = connection.prepareStatement(query);
rs1 = ps.executeQuery();
System.out.println("Written Successfully");
}
public static void main (String args[]) throws SQLException,ClassNotFoundException
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
new ConnectAndSearchDB();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Here is the Names table:
I highly suspect that using rs1 = ps.executeQuery(); to insert/update the database is the course of your issue, you should be using int count = ps.executeUpdate();
See PreparedStatement#executeUpdate for more details
Not an answer per se, but a series of extended comments about some issues with the overall approach...
Lesson #1 - Resource management
If you open it, you should close it...
String query = "SELECT * from NAMES";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
try (ResultSet rs = s.executeQuery()) {
boolean matchfound = false;
while(rs.next())
{
if(rs.getString(1).equals(name))
{
matchfound = true;
System.out.println("The name "+name+" is found in the Database");
break;
}
}
if(matchfound == false)
{
System.out.println("Match Not Found");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
See The try-with-resources Statement for more details...
I'd also reconsider using a single Connection, while a Connection pool might be overkill for this problem, you could simply open and close a Connection as need, but remember, there is an overhead incurred when doing this...
Lesson #2 - Don't do what the database can do better
String query = "SELECT count(*) from NAMES where name=?";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, name);
try (ResultSet rs = s.executeQuery()) {
boolean matchfound = false;
if (rs.next())
{
if(rs.getLong(1) > 0)
{
matchfound = true;
System.out.println("The name "+name+" is found in the Database");
}
}
if(!matchfound)
{
System.out.println("Match Not Found");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
Lesson #3 - Make use of your PreapredStatement...
Instead of...
query = "INSERT INTO NAMES VALUES('"+fieldAdd.getText()+"')";
Use...
query = "INSERT INTO NAMES VALUES(?)";
//...
ps.setString(1, fieldAdd.getText());
See Using Prepared Statements

mysql query not executing in java but executing in my SQLYog

can anyone please tell why the following update query which is working perfectly when executed directly from my SQLYog editor, but not executing from java. it is not giving any exception but not updating into the database.
this the update query
UPDATE hotel_tables SET hotel_tables.status='reserved' WHERE hotel_tables.section='pub' AND tableno='4' AND ('4' NOT IN (SELECT tableno FROM table_orders WHERE outlet='pub'))
Java code
public static void main(String[] args) throws Exception {
int update = new Dbhandler().update("UPDATE hotel_tables SET hotel_tables.status='reserved' WHERE hotel_tables.section='pub' AND tableno='4' AND ('4' NOT IN (SELECT tableno FROM table_orders WHERE outlet='pub'))");
}
public int update(String Query)throws Exception
{
try
{
cn=getconn();
stmt=(Statement) cn.createStatement();
n=stmt.executeUpdate(Query);
stmt.close();
}
catch(Exception e)
{
e.printStackTrace();
throw(e);
}
finally
{
cn.close();
}
return n;
}
public Connection getconn()
{
try
{
Class.forName(driver).newInstance();
String url="jdbc:mysql://localhost/kot?user=root&password=root";
cn=(Connection) DriverManager.getConnection(url);
}
catch(Exception e)
{
System.out.println("DBHandler ERROR:"+e);
}
return cn;
}
This is how I used to do it before I switched to Spring's JdbcTemplate framework. Maybe this will help. It looks very similar to yours.
public static int runUpdate(String query, DataSource ds, Object... params) throws SQLException {
int rowsAffected = 0;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ds.getConnection();
stmt = conn.prepareStatement(query);
int paramCount = 1;
for (Object param : params) {
stmt.setObject(paramCount++, param);
}
rowsAffected = stmt.executeUpdate();
conn.commit();
} catch (SQLException sqle) {
throw sqle;
//log error
} finally {
closeConnections(conn, stmt, null);
}
return rowsAffected;
}
There are some subtle differences. I do a commit, though autoCommit is the default.
Try like this:
DriverManager.getConnection("jdbc:mysql://localhost:3306/kot","root","root");

Akka Actors fails, VerifyError: Inconsistent stackmap frames at branch target

I have a Java application where I use Akka Typed Actors. The code has no errors in Eclipse, but when I start my application it crashes and prints this error:
Exception in thread "main" java.lang.VerifyError: Inconsistent stackmap frames at branch target 266 in method com.example.actors.DBActor.getItems(Lorg/joda/time/DateTime;Lorg/joda/time/DateTime;)I at offset 170
at com.example.ui.Main$1.create(Main.java:31)
at akka.actor.TypedActor$$anonfun$newInstance$3.apply(TypedActor.scala:677)
at akka.actor.TypedActor$$anonfun$newInstance$3.apply(TypedActor.scala:677)
at akka.actor.TypedActor$.newTypedActor(TypedActor.scala:847)
at akka.actor.TypedActor$$anonfun$newInstance$1.apply(TypedActor.scala:601)
at akka.actor.TypedActor$$anonfun$newInstance$1.apply(TypedActor.scala:601)
at akka.actor.LocalActorRef.akka$actor$LocalActorRef$$newActor(ActorRef.scala:1084)
at akka.actor.LocalActorRef$$anonfun$2.apply(ActorRef.scala:628)
at akka.actor.LocalActorRef$$anonfun$2.apply(ActorRef.scala:628)
at akka.util.ReentrantGuard.withGuard(LockUtil.scala:20)
at akka.actor.LocalActorRef.<init>(ActorRef.scala:628)
at akka.actor.Actor$.actorOf(Actor.scala:249)
at akka.actor.TypedActor$.newInstance(TypedActor.scala:677)
at akka.actor.TypedActor.newInstance(TypedActor.scala)
at com.example.ui.Main.main(Main.java:29)
I don't understand what can be wrong. I have check my com.example.actors.DBActor.getItems() but there is no error in it. What could be wrong?
UPDATE
Below is example on code where I get this error.
I have these jar-files on the "Build path" in Eclipse:
derby.jar (from JDK7) (only an in-memory database is used in this example)
akka-actor-1.2.jar
akka-typed-actor-1.2.jar
aspectwerkz-2.2.3.jar
scala-library.jar
Here is the code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import akka.actor.TypedActor;
import akka.actor.TypedActorFactory;
public class App {
public App() {
TypedActor.newInstance(Backend.class, new TypedActorFactory() {
public TypedActor create() {
return new DataActor();
}
});
}
class DataActor extends TypedActor implements Backend {
#Override
public void insertData(String msg) {
final String sqlSelect = "SELECT msg FROM SESSION.messages "+
"WHERE to_user_id = ? AND from_user_id = ?";
final String connectionURL = "jdbc:derby:memory:memdatabase;create=true";
/* if this declaration is moved to where the string is used
in the conditional, the conditional can be used */
String result;
try(Connection conn = DriverManager.getConnection(connectionURL);) {
try(PreparedStatement ps = conn.prepareStatement(sqlSelect);
ResultSet rs = new QueryHelper(ps)
.integer(13).integer(26).executeQuery();) {
/* this doesn't work */
result = (rs.next()) ? rs.getString("text")
: null;
/* but this work:
String result = (rs.next()) ? rs.getString("text")
: null;
*/
/* this works fine
while(rs.next()) {
result = rs.getString("msg");
} */
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
class QueryHelper {
private final PreparedStatement ps;
private int index = 1;
public QueryHelper(PreparedStatement ps) {
this.ps = ps;
}
public QueryHelper integer(int param) throws SQLException {
ps.setInt(index++, param);
return this;
}
public ResultSet executeQuery() throws SQLException {
return ps.executeQuery();
}
}
public interface Backend {
public void insertData(String text);
}
public static void main(String[] args) {
new App();
}
}
I have found out that this bug is in places where I use multiple resources in a single Java 7 try-with-resources statement.
E.g. this code will have the bug:
try (Connection conn = DriverManager.getConnection(connURL);
PreparedStatement ps = conn.prepareStatement(sql);) {
// do something
} catch (SQLException e) {
e.printStackTrace();
}
and a workaround would look like:
try (Connection conn = DriverManager.getConnection(connURL);) {
try (PreparedStatement ps = conn.prepareStatement(sql);) {
// do something
}
} catch (SQLException e) {
e.printStackTrace();
}
run java with the option -XX:-UseSplitVerifier

Categories