try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/gledi", "root", "root");
String sql = "SELECT MAX(NR) from ROOT.GLEDI";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
String nr1= rs.getString("MAX(NR)"); // here is the whole problem !!!!! how can i fix it
text.setText(nr1);
}
} catch (Exception e) {
}
Give it a name and look it up.
Is that column a String type or a number?
Empty catch blocks are wrong. Print or log the stack trace. You'll never know if an exception is thrown otherwise.
Sure you don't want select count(*) from root.gledi? This query looks wrong to me.
You don't close Connection, Statement, or ResultSet in a finally block, as you should.
You should encapsulate this code in a method and give it a Connection, not create it every time.
So little code, so many errors.
Here's how I might write it:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* JdbcDemo
* #author Michael
* #link http://stackoverflow.com/questions/21205161/how-to-fix-a-db-probblem-in-java-with-derby-db/21205183#21205183
* #since 1/18/14 9:51 AM
*/
public class JdbcDemo {
private static final String SELECT_MAX_ROW_NUMBER = "SELECT MAX(NR) as maxnr from ROOT.GLEDI";
private Connection connection;
public JdbcDemo(Connection connection) {
this.connection = connection;
}
public String getMaxRowNumber() {
String maxRowNumber = "";
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = connection.prepareStatement(SELECT_MAX_ROW_NUMBER);
rs = ps.executeQuery();
while (rs.next()) {
maxRowNumber = rs.getString("maxnr");
}
} catch (Exception e) {
e.printStackTrace(); // better to log this.
maxRowNumber = "";
} finally {
close(rs);
close(ps);
}
return maxRowNumber;
}
// belongs in a database utility class
public static void close(Statement st) {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace(); // better to log this
}
}
// belongs in a database utility class
public static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace(); // better to log this
}
}
}
Related
I would like to ask how to make Connection con = getConnection(); becaome a primer or main variable so that it would not connect to SQL database every function made. Because as you can see on my codes, every function/class has Connection con = getConnection(); so it connects to the database every function. It makes my program process slowly. Please help thank you.
package march30;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
public class sqltesting {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
get();
}
public static void lookup() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename where id=6");
ResultSet result = statement.executeQuery();
if (result.next()) {
System.out.println("First Name: " + result.getString("first"));
System.out.println("Last Name: " + result.getString("last"));
}
else {
System.out.println("No Data Found");
}
} catch (Exception e) {}
}
public static ArrayList<String> get() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while (result.next()) {
System.out.print(result.getString("first"));
System.out.print(" ");
System.out.println(result.getString("last"));
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
System.out.println(Arrays.asList(array));
return array;
} catch (Exception e) {System.out.println((e));}
return null;
}
public static void update() throws Exception{
final int idnum = 2;
final String var1 = "New";
final String var2 = "Name";
try {
Connection con = getConnection();
PreparedStatement updated = con.prepareStatement("update tablename set first=?, last=? where id=?");
updated.setString(1, var1);
updated.setString(2, var2);
updated.setInt(3, idnum);
updated.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Update Completed");
}
}
public static void delete() throws Exception{
final int idnum = 7;
try {
Connection con = getConnection();
PreparedStatement deleted = con.prepareStatement("Delete from tablename where id=?");
deleted.setInt(1, idnum);
deleted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Delete Completed");
}
}
public static void post() throws Exception{
final String var1 = "Albert";
final String var2 = "Reyes";
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO tablename (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Insert Completed");
}
}
public static void createTable() throws Exception {
try {
Connection con = getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))");
create.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Function Completed");
}
}
public static Connection getConnection() throws Exception{
try {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://xxxxxxxx.amazonaws.com:3306/pointofsale";
String username = "xxxxx";
String password = "xxxxxx";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
To solve your problem you need to store a Connection object in your sqltesting class as a class member. You then need to reference the Connection object instead of getConnection(). It's also worth mentioning that Connection is a AutoClosable object so you need to close this resource when you're done with it, I.E; on application disposal. You also might want to consider using a connection pooling API like Hikari or C3P0 so you can open and close connections when you need them instead of having 1 open for a long time.
class SQLTesting {
private final Connection connection;
public SQLTesting(Connection connection) {
this.connection = connection;
}
public SQLTesting() {
this(getConnection());
}
// other methods
private Connection getConnection() {
// your method to create connection, rename to createConnection maybe.
}
}
I have a program that queries a database using different jdbc drivers. This error is specific to the MySQL driver.
Here's the basic rundown.
I have another query runner class that uses a postgresql jdbc driver that works just fine. Note the line conn.close(); this works fine on my postgresql query runner, but for this SQL runner it comes up with the error.
I have removed the line conn.close(); and this code works fine, but over time it accumulates sleeping connections in the database. How can I fix this?
New Relic is a third party application that I am feeding data to, if you dont know what it is, don't worry it's not very relevant to this error.
MAIN CLASS
public class JavaPlugin {
public static void main(String[] args) {
try {
Runner runner = new Runner();
runner.add(new MonitorAgentFactory());
runner.setupAndRun(); // never returns
}
catch (ConfigurationException e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(-1);
}
}
}
MYSQL QUERY RUNNER CLASS
import com.newrelic.metrics.publish.util.Logger;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLQueryRunner {
private static final Logger logger = Logger.getLogger(MySQLQueryRunner.class);
private String connectionStr;
private String username;
private String password;
public MySQLQueryRunner(String host, long port, String database, String username, String password) {
this.connectionStr = "jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=false";
this.username = username;
this.password = password;
}
private void logError(String message) {
logger.error(new Object[]{message});
}
private void logDebugger(String message) {
logger.debug(new Object[]{message});
}
private Connection establishConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
logError("MySQL Driver could not be found");
e.printStackTrace();
return null;
}
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionStr, username, password);
logDebugger("Connection established: " + connectionStr + " using " + username);
} catch (SQLException e) {
logError("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
return connection;
}
public ResultSet run(String query) {
Connection conn = establishConnection();
if (conn == null) {
logError("Connection could not be established");
return null;
}
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
conn.close();
return rs;
} catch (SQLException e) {
logError("Failed to collect data from database");
e.printStackTrace();
return null;
}
}
}
AGENT CLASS
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import com.newrelic.metrics.publish.Agent;
public class LocalAgent extends Agent {
private MySQLQueryRunner queryRunner;
private String name;
private Map<String, Object> thresholds;
private int intervalDuration;
private int intervalCount;
public LocalAgent(String name, String host, long port, String database, String username, String password, Map<String, Object> thresholds, int intervalDuration) {
super("com.mbt.local", "1.0.0");
this.name = name;
this.queryRunner = new MySQLQueryRunner(host, port, database, username, password);
// this.eventPusher = new NewRelicEvent();
this.thresholds = thresholds;
this.intervalDuration = intervalDuration;
this.intervalCount = 0;
}
/**
* Description of query
*/
private void eventTestOne() {
String query = "select count(1) as jerky from information_schema.tables;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestOne");
event.add("jerky", rs.getInt("jerky"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* blah
*/
private void eventTestTwo() {
String query = "SELECT maxlen FROM information_schema.CHARACTER_SETS;";
ResultSet rs = queryRunner.run(query);
try {
while (rs.next()) {
NewRelicEvent event = new NewRelicEvent("localTestTwo");
event.add("beef", rs.getString("maxlen"));
event.push();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void pollCycle() {
if (this.intervalCount % this.intervalDuration == 0) {
eventTestOne();
eventTestTwo();
this.intervalCount = 0;
}
// Always incrementing intervalCount, keeping track of poll cycles that have passed
this.intervalCount++;
}
#Override
public String getAgentName() {
return this.name;
}
}
The problem is that you are trying to access the ResultSet after the connection is closed.
You should open and close the connection in the method that is calling run() this way the connection will be open when you access and loop through the Resultset and close it in the finally block of the calling method.
Even better would be if you can just loop through the ResultSet in the run() method and add the data to an object and return the object, this way you can close it in the finally block of the run() method.
I wrote stored procedure in MySQL which looks like this (it works):
DELIMITER //
CREATE PROCEDURE getBrandRows(
IN pBrand VARCHAR(30),
OUT pName VARCHAR(150),
OUT pType VARCHAR(200),
OUT pRetailPrice FLOAT)
BEGIN
SELECT p_name, p_type, p_retailprice INTO pName, pType, pRetailPrice
FROM part
WHERE p_brand LIKE pBrand;
END//
DELIMITER ;
I try to return multiple results and display them. I've tried many ways described here on Stack and in Internet but that does not help me. I have edited my entire code and created a simple one so you can guys paste it and compile. It should work but with error. Here is the code:
package javamysqlstoredprocedures;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class JavaMySqlStoredProcedures {
private final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private final String DB_URL = "jdbc:mysql://anton869.linuxpl.eu:3306/"
+ "anton869_cars?noAccessToProcedureBodies=true";
private final String DB_USER = "xxx";
private final String DB_PASSWORD = "xxx";
class CallStoredProcedureAndSaveXmlFile extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() {
displaySql();
return null;
}
#Override
public void done() {
}
private void displaySql() {
try {
System.out.println("Connecting to MySQL database...");
Class.forName(DEFAULT_DRIVER);
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD)) {
System.out.println("Connected to MySQL database");
CallableStatement cs = conn.prepareCall("{CALL getBrandRows("
+ "?, ?, ?, ?)}");
cs.setString(1, "Brand#13");
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(3, Types.VARCHAR);
cs.registerOutParameter(4, Types.FLOAT);
boolean results = cs.execute();
while (results) {
ResultSet rs = cs.getResultSet();
while (rs.next()) {
System.out.println("p_name=" + rs.getString("p_name"));
System.out.println("p_type=" + rs.getString("p_type"));
System.out.println("p_retailprice=" + rs
.getFloat("p_retailprice"));
}
rs.close();
results = cs.getMoreResults();
}
cs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public JavaMySqlStoredProcedures() {
new CallStoredProcedureAndSaveXmlFile().execute();
}
public static void main(String[] args) {
JavaMySqlStoredProcedures jmssp = new JavaMySqlStoredProcedures();
}
}
ResultSet can handle multiple records.I found some errors in your code.Try these steps
Move your all close method to finally block.
try {
//do something
} catch (Exception e) {
//do something
} finally {
try{
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
//do something
}
}
You can put your result into List. See sample
List<YourObject> list = new ArrayList<YourObject>();
while (rs.next()) {
YourObject obj = new Your Object();
obj.setName(rs.getString("p_name"));
obj.setType(rs.getString("p_type"));
obj.setRetailPrice(rs.getFloat("p_retailprice"));
list.add(obj);
}
Make sure your query is correct and database connection is Ok.
Don't use IN or OUT parameter if you just simply want to display result. And also you should add '%%' in your LIKE clause with the help of CONCAT function. Please try this one:
DELIMITER //
CREATE PROCEDURE getBrandRows(
pBrand VARCHAR(30)
)
BEGIN
SELECT p_name, p_type, p_retailprice INTO pName, pType, pRetailPrice
FROM part
WHERE p_brand LIKE CONCAT("%", pBrand, "%");
END//
DELIMITER ;
I am posting correct solution to everybody who have smiliar problem:
1. Corrected Stored Procedure:
DELIMITER //
CREATE PROCEDURE getBrandRows(
IN pBrand VARCHAR(30))
BEGIN
SELECT p_name, p_type, p_retailprice
FROM part
WHERE p_brand = pBrand;
END//
DELIMITER ;
2. Corrected Java code:
package javamysqlstoredprocedures;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class JavaMySqlStoredProcedures {
private final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private final String DB_URL = "jdbc:mysql://anton869.linuxpl.eu:3306/"
+ "anton869_cars?noAccessToProcedureBodies=true";
private final String DB_USER = "xxx";
private final String DB_PASSWORD = "xxx";
class CallStoredProcedureAndSaveXmlFile extends SwingWorker<Void, Void> {
#Override
public Void doInBackground() {
displaySql();
return null;
}
#Override
public void done() {
}
private void displaySql() {
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
try {
System.out.println("Connecting to MySQL database...");
Class.forName(DEFAULT_DRIVER);
conn = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASSWORD);
System.out.println("Connected to MySQL database");
cs = conn.prepareCall("{CALL getBrandRows(?)}");
cs.setString(1, "Brand#13");
boolean results = cs.execute();
while (results) {
rs = cs.getResultSet();
while (rs.next()) {
System.out.println("p_name=" + rs.getString("p_name"));
System.out.println("p_type=" + rs.getString("p_type"));
System.out.println("p_retailprice=" + rs.getFloat(
"p_retailprice"));
}
results = cs.getMoreResults();
}
} catch (SQLException | ClassNotFoundException e) {
} finally {
try {
if (rs != null ) rs.close();
if (cs != null) cs.close();
if (conn != null) conn.close();
} catch (SQLException e) {
}
}
}
public JavaMySqlStoredProcedures() {
new CallStoredProcedureAndSaveXmlFile().execute();
}
public static void main(String[] args) {
JavaMySqlStoredProcedures jmssp = new JavaMySqlStoredProcedures();
}
}
Your stored procedure returns more than one row. Just correct logic behind your select query inside the stored procedure it should return only one row.
here how to return multiple value
This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 7 years ago.
java.sql.SQLException: Parameter index out of range (1 > number of parameters,
which is 0)
For the following code, what kind of parameter change is required to make the code run?
package com.chen.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class SqlHelper {
private static Connection conn = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
private static String url = "jdbc:mysql://localhost:3306/userdata";
private static String username1 = "root";
private static String password1 = "root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static Connection getConnection() {
try {
conn = DriverManager.getConnection(url, username1, password1);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void executeUpdate(String sql, String[] parameters) {
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
if (parameters != null) {
for (int i = 0; i < parameters.length; i++) {
ps.setString(i+1 , parameters[i]);
}
}
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
close(rs,ps,conn);
}
}
public static ResultSet executeQuery(String sql,String[]parameters){
try{
conn=getConnection();
ps=conn.prepareStatement(sql);
if(parameters!=null&&!parameters.equals("")){
for(int i=0;i<parameters.length;i++){
ps.setString(i+1,parameters[i]);
}
}
rs=ps.executeQuery();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}finally{
//close(rs,ps,conn);
}
return rs;
}
public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
ps = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static Connection getConn() {
return conn;
}
public static PreparedStatement getPs() {
return ps;
}
public static ResultSet getRs() {
return rs;
}
}
Below is the error stack:
//java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:904)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3797)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3779)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4600)
at com.chen.util.SqlHelper.executeQuery(SqlHelper.java:100)
at com.chen.services.UserService.checkUser(UserService.java:22)
at com.chen.controller.ControllerServlet.doGet(ControllerServlet.java:33)
at
package com.chen.services;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.chen.domain.User;
import com.chen.util.SqlHelper;
public class UserService {
// 用checkUser()来判断用户是否存在
public boolean checkUser(User user) {
boolean b = false;
// 使用SqlHelper来完成查询任务
String sql = "select * from user where username=? and password=?";
String parameters[] = { user.getUsername(), user.getPassowrd() };
ResultSet rs = SqlHelper.executeQuery("sql", parameters);
// 根据rs来判断该用户是否存在
try {
if (rs.next()) {
b = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return b;
}
public ArrayList getUserByPage(int pageNow, int pageSize) {
ArrayList<User> arr = new ArrayList<User>();
// 查询sql
//String sql = "select * from user where id>3 order by id limit 20";
String sql="select sql_calc_found_rows * from user limit 0,10";
ResultSet rs = SqlHelper.executeQuery(sql, null);
// 二次封装 把 ResultSet -->User对象-->Arraylist(集合)
try {
while (rs.next()) {
User u = new User();
try {
u.setId(rs.getInt(1));
u.setUsername(rs.getString(2));
u.setPassowrd(rs.getString(3));
// 一定记住 u-->ArrayList
arr.add(u);
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return arr;
}
public int getPageCount(int pageSize) {
String sql = "select * from user";
int rowCount = 0;
ResultSet rs = SqlHelper.executeQuery(sql, null);
try {
rs.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rowCount = rs.getInt(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return (rowCount - 1) / pageSize + 1;
}
//删除用户
public boolean deleUser(String id){
boolean b=true;
String sql="delete from user where id=?";
String parameters[]={id};;
try {
SqlHelper.executeUpdate(sql, parameters);
} catch (Exception e) {
b=false;
}
return b;
}
//用过id获取用户数据
public User getUserById(String id){
User user=new User();
String sql="select * from user where id= ?";
String parameters[]={id};
ResultSet rs=SqlHelper.executeQuery(sql, parameters);
try {
if(rs.next()){
user.setId(rs.getInt(1));
user.setUsername(rs.getString(2));
user.setPassowrd(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
SqlHelper.close(rs, SqlHelper.getPs(), SqlHelper.getConn());
}
return user;
}
//修改用户
public boolean updateUser(User user){
boolean b=true;
String sql="update user set username=?,password=? where id=?";
String parameters[]={user.getUsername(),user.getPassowrd(),user.getId()+""};
try {
SqlHelper.executeUpdate(sql, parameters);
} catch (Exception e) {
b=false;
}
return b;
}
}
Replace this:
ResultSet rs = SqlHelper.executeQuery("sql", parameters);
With:
ResultSet rs = SqlHelper.executeQuery(sql, parameters);
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