Mysql exception"out of range"? - java

I am working in swing based project and use prepared statement but it give exception like out of range and when i using parameters and do not put '?' but simply ? then show exception like"
jdbc syntax error check the manual near '?,?' at line one " i am so confused what is happening.Check my code what is wrong?
private void AddActionPerformed(java.awt.event.ActionEvent evt) {
if (((JTextField) chose.getDateEditor().getUiComponent()).getText() == null) {
String sql = "INSERT INTO expance1 ( Breakfast,Date) VALUES (?,?)";
} else {
String sql = "INSERT INTO expance1 ( Breakfast,Date) VALUES (?,?)";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, breakfast.getText());
pst.setString(2, ((JTextField) chose.getDateEditor().getUiComponent()).getText());
pst.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "insert sucessfully");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
} finally {
try {
rs.close();
pst.close();
} catch (Exception e) {
}
}
}
}

Replace
pst.executeUpdate(sql);
by
pst.executeUpdate();
The SQL query has already been passed to the statement when preparing it. You must not pass it a second time. Passing it executes the literal SQL query, not the prepared one.

Related

Trouble with SQL query

I'm new in database and sql, and just trying to figure it all out in Java, but I got stuck with some minor problem, I'm trying to remove one record in db, with id that is given as method parameter, like this, but it's not working
#Override
public void removeCustomer(int number) {
Statement statement = null;
try {
statement = connection.createStatement();
statement.executeUpdate("DELETE FROM Customers WHERE id='number'");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try{
if(statement != null) statement.close();
} catch (SQLException e ) {
e.printStackTrace();
}
}
}
It does work, when I write in SQL query " ... WHERE id='2'";
But I want to be able to pass the number from method parameter.
Anyone could help?
You can use PreparedStatement like so :
try(PreparedStatement stm = connection.createStatement("DELETE FROM Customers WHERE id=?")){
stm.setInt(1, number);
stm.executeUpdate();
}
//.. catch and finally
Note
It does work, when I write in SQL query " ... WHERE id='2'";
If in case your id is a varchar you can pass a string to the statement by using setString instead of setInt, but I don't suggest to use string for id

Selecting all data using LIKE in java by getting the string in jtextfield

try{
String Sql ="Select * from learners_info where lrn LIKE %?% ";
pst=conn.prepareStatement(Sql);
pst.setString(1, txtSearch.getText());
System.out.print(pst);
rs = pst.executeQuery();
DefaultTableModel ts = (DefaultTableModel)tableSearch.getModel();
ts.setRowCount(0);
while (rs.next()){
Object searchTable[] = {
rs.getInt("lrn"),
rs.getString("learner_firstname"),
rs.getString("learner_middlename"),
rs.getString("learner_lastname"),
};
ts.addRow(searchTable);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Invalid info idnumber");
e.printStackTrace();
}
//
finally {
try {
rs.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
pst.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is I cant find the proper String to use for me to get the LIKE terms in the SQL from text field
**Using this String **
String Sql ="Select * from learners_info where lrn LIKE %?% ";
I seem to get this error :
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3813)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3795)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4616)
And if I try this String
String Sql ="Select * from learners_info where lrn LIKE '%'?'%' ";
I printed what kind of string is being used using system.out and it shows this.
com.mysql.jdbc.JDBC4PreparedStatement#414a0b8f: Select * from learners_info where lrn LIKE '%''1411237''%'
this query works but it doesn't seem to return any values
I'm sorry cause I'm still new to database in java.
Remove the '%' parts from your SQL String. Try with this :
String Sql ="Select * from learners_info where lrn LIKE ?";
Then try passing the %s along with your String value in your PreparedStatement setString() method

Getting MySql command result in servlet java

Basically I am trying to find how many people in mysql database are registered by a specific name using SELECT command with my java program. The command executes without any error but the result is something different than I have in my db.
Here is my java code I am using to get UIDs:
public void usernameAvail_fun(){
String query = "SELECT UID FROM db.tb WHERE UFN=\"myuid\"";
ResultSet ursa;
try {
ursa = st.executeQuery(query);
System.out.println(ursa.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
and i happen to get the result as: com.mysql.jdbc.JDBC42ResultSet#11719758
You are printing a java object so output is there. If you want to print uid use following statement -
while (ursa.next()){
System.out.println(ursa.getString(1));
}
Initialize ursa to null first.
adding a PreparedStatement
public void usernameAvail_fun(){
String query = "SELECT UID FROM db.tb WHERE UFN=\"myuid\"";
ResultSet ursa= null;
try {
PreparedStatement stmt = con.prepareStatement(query);
ursa= stmt.executeQuery();
while(ursa.next()) //print
{
ursa.getString(1); //or ursa.getString("//your column name");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}

Inserting field values into database

I can't seem to figure out why I'm getting this exception: SQLException: Parameter index out of range (1 > number of parameters, which is 0). My mysql connector version is 5.1.29. Is this possible a problem with this version, or am I not properly setting up the query?
Scratch:
public void actionPerformed(ActionEvent e) {
String query = "INSERT INTO racebikes"
+ "(bikename, country_of_origin, cost) VALUES"
+ "(?,?,?)";
try {
statement.setString(1, (String)winners_combo_box.getSelectedItem());
statement.setString(2, winner_fields[0].getText());
statement.setFloat(3, Float.parseFloat(winner_fields[1].getSelectedText()));
statement.executeUpdate(query);
} catch(SQLException e1) {
e1.printStackTrace();
}
}
You're not assigning a value to statement in that method, and you're using the overload of executeUpdate from Statement... rather than the parameterless one in PreparedStatement.
I suspect you actually want to assign the statement using Connection.prepareStatement:
public void actionPerformed(ActionEvent e) {
String query = "INSERT INTO racebikes"
+ "(bikename, country_of_origin, cost) VALUES"
+ "(?,?,?)";
// TODO: Connection management?
PreparedStatement statement = conn.prepareStatement(query);
try {
statement.setString(1, (String)winners_combo_box.getSelectedItem());
statement.setString(2, winner_fields[0].getText());
statement.setFloat(3, Float.parseFloat(winner_fields[1].getSelectedText()));
statement.executeUpdate();
} catch(SQLException e1) {
e1.printStackTrace();
// TODO: Don't just pretend it worked...
} finally {
statement.close();
}
}
You shouldn't be trying to reuse a statement, basically. Personally I'd try not to reuse a connection, either, using connection pooling to handle reuse of the underlying connection, but that's a different matter.

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);
}
}
}
}

Categories