PreparedStatement not executing! - java

So odd! :P
connection = appDatabase_.getDatabase().getConnection();
PreparedStatement updateStmt = connection.prepareStatement
("UPDATE " + getTableName() + " SET " + column
+ " = ? WHERE " + ID + " = ?");
Got this chunk of code. After this comes some hard coded "set bytes" and "set int" statements.
And then an execute(). Pretty simple right?
Occasionally the prepared statement just fails to execute and the app acts very oddly (hard to explain how). Why and when would this happen? Maybe if the connection is closed?
Not sure what to think atm.
Thanks SO!

Well, since you didn't show us your try/catch and I know java.sql classes are full of declared checked exceptions, my guess would be you're eating exceptions somewhere.

Related

Syntax error in my from clause

Im getting this :
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in FROM clause.
For my code:
ResultSet results = state.executeQuery("SELECT * FROM User" + "WHERE user_name = '" +
txtUser.getText() + "'AND password = '" + txtPass.getText() + "'" );
I have already declared all of the variables, and i suspect the error has something to do with the structure however I am unsure. Thanks
If you pay close attention to your code on this line:
"SELECT * FROM User" + "WHERE user_name
You can see that this results in
SELECT * FROM UserWHERE user_name
You need to add in a space.
In addition you're opening yourself to SQL injection attacks by building your statement like this. You should really use a PreparedStatement and use placeholder. You also won't need to build the statement by hand which would help you avoid this very issue.

Is it safe to add a new line charactor (\n) in the sql query?

StringBuilder sql = new StringBuilder();
sql.append("SELECT C.ID,\n" +
" CODE\n" +
" FROM DB.TEATABLE C\n" +
" LEFT JOIN\n" +
" (SELECT IT.TEA,\n" +
" IT.COFFEETYPE,\n" +
" XREF.AUSTIN_COFFEE_LEAF_CODE AS LEAFCODE\n" +
" FROM DB.COFFEE_AUSTIN_XREF XREF,\n" +
" DB.INDIAPLAN TP,\n" +
" DB.COFFEE IT,\n" +
" DB.TEATABLE C\n" +
" WHERE C.ID = IT.TEA\n" +
" AND IT.COFFEETYPE = 'RIL'\n" +
" AND IT.INDIAPLANID =TP.ID");
con = getConnection();
pstmt = con.prepareStatement(sql.toString());
rs = pstmt.executeQuery();
We used to add new line charactor as above. Is it safe to add \n character in the query (in Oracle)?
Yes! But make sure your newlines are actually newlines.
I was trouble shooting for 3 hours thinking it was my sql syntax
because I used:
String N = System.getProperty("line.seperator");
I thought I had a newline character,
but I was actually inserting nulls into my statement.
Error Messages Included:
1:
org.postgresql.util.PSQLException:
ERROR: syntax error at or near "NULLnull"
2:
org.postgresql.util.PSQLException:
ERROR: conflicting NULL/NOT NULL declarations
for column "nullid" of table "t_1"
3:
org.postgresql.util.PSQLException:
ERROR: syntax error at or near "KEYnull"
4:
org.postgresql.util.PSQLException:
ERROR: syntax error at or near "null"
I thought I was my primary key statement:
id SERIAL PRIMARY KEY NOT NULL
For longer than I would like to admit.
Yes, it is perfectly fine to add newlines (\n or \r\n) to your query. Most parsers consider newlines as whitespace (just like a space or tab), and so does the one used by Oracle (and all other database I have used).
You have already proven this, because based on your comments your company already does this (and probably has so for years). I'm curious as to why you think it could be unsafe. Because obviously it works, and if it would be unsafe, Oracle would disallow it with a clear error.
Although very subjective, it could be better than not doing it, as it allows for a easier visual inspection if all lines end in whitespace. Consider the difference between:
Oops, no space
"select *" +
"from table"
Space
"select * " +
"from table"
Linebreak
"select *\n" +
"from table"
The difference between 1 and 2 is smaller than between 1 and 3. Especially in long queries this might matter to see if you forgot whitespace which might either lead to a syntax error, or worse to incorrect query behavior.
On the other hand, the newlines are extra visual clutter that might distract from reading the query. When in doubt, go with what is the norm or codestyle in your company.

Bad SQLITE update Performance

I am fairly new in SQL(now working on SQLITE application) and it is a section in my app when i try this piece of Code:
public void addSong(LibrarySong song){
for(int i=0; i<intoPanel.getComponentCount(); i++) //Check if doublicates exist
if(song.getName().equals(intoPanel.getComponent(i).getName()))
return;
intoPanel.add(song);
//Add the song to the database table
try{
Container.DataBase.connection.prepareStatement("INSERT INTO '"
+ Container.libWindow.libInfoWindow.currentLib.getName()+ "'" //Table Name
+ " (PATH,STARS,DATE,HOUR) VALUES ('"
+ song.getName() + "'," + song.stars + ",'"
+ song.dateCreated + "','" + song.hourCreated + "')").executeUpdate();
}catch(SQLException sql){ sql.printStackTrace(); };
}
The Problem:
The above method just add the song to a Jtable and then to database table.The problem is that the performance is too bad for the database.Why might this happen? i use the statement somewhere wrong or i have to to the update with different way?Thanks for reply.
The most expensive part of accessing a database is not the execution of the statement itself, but all the synchronizations done for transactions.
By default, each SQL command is put into an automatic transaction, so you get the overhead for all of them.
If you have multiple updates, you should group them into a single transaction:
Container.DataBase.connection.setAutoCommit(false);
...
for (...)
addSong(...);
Container.DataBase.connection.commit();
Basically the problem boils down to that every write to disc is done by sqlite itself in default mode
you could enable
PRAGMA journal_mode = WAL
PRAGMA synchronous = NORMAL
To make use of the operating system disc buffer.
Just remember to flush/commit everything regularly or at break points after inserts. Only risk is if there is sudden powerloss or reboot, your database might end up corrupted.
https://www.sqlite.org/atomiccommit.html
I think, that the component usage is suboptimal: the first for-loop.
Use a
Set<String> songNames = new HashSet<>();
if (songNames.contains(song.getName())) { return; }
songNames.add(song.getName());
Or maybe a Map for other uses.
And use the prepared statement with placeholders ?. This escapes single quotes too. And is safer.

JAVA update statement using WHERE and a variable: invalid character constant

just kinda struggling with identifying the id during the piece update. I pass the id as a var and am trying to use it in conjunction with the WHERE statement and cant seem to figure out the correct syntax
String update = "UPDATE LawnMowers"+ " SET LMPrice = '"+returnedPrice+"' " + " WHERE LMID = '"+returnedID+'";
the return id is the issue, and the error is "invalid character constant". I believe the issue is normally the statement would be:
"WHERE LMID = int/double.ect"; rather then using " WHERE LMID = '"+varr+'"; errors and adding the additional " or )" ect options I have tried dont work either. Just wondering if any one had some insight
my DB is on Godaddy
thanks for reading
I think your statement should end
+ returnedID + "'";
Yours currently ends
+returnedID+'";
Also please read about prepared statements, these are much easier to use and leave you at far less risk of SQLi security vulnerabilities. It would look something like this:
String update = "UPDATE LawnMowers SET LMPrice = ? WHERE LMID = ?";
updateStatement = con.prepareStatement(update);
updateStatement.setInt(1, returnedPrice);
updateStatement.setInt(2, returnedId);
updateStatement.executeUpdate();

NullPointerException from Connection.preparedStatement for SQLite JDBC

what I'm trying to do is get a ResultSet from a SQL statement from which then I can derive certain values. What I seem to be having troubles with is the preparing of the prepared statement which occurs at this line.
String sql = "SELECT " + dataState + " FROM " + table + whereState + ";";
java.sql.PreparedStatement prep = conn.prepareStatement(sql); // Error here
I've already checked that the variable conn is not null. All the values in the statement are not null and the stack trace shows this.
java.lang.NullPointerException
at org.sqlite.PrepStmt.(PrepStmt.java:37)
at org.sqlite.Conn.prepareStatement(Conn.java:231)
at org.sqlite.Conn.prepareStatement(Conn.java:224)
at org.sqlite.Conn.prepareStatement(Conn.java:213)
at org.utilities.storagemethods.SQLiteMethod.load(SQLiteMethod.java:223)
at org.utilities.DataManager.load(DataManager.java:97)
at org.utilities.Test.main(Test.java:21)
A print of the sql statement shows that it gives this.
SELECT testString, testBool, testObj FROM testTable WHERE testInt=?;
You can ascertain the values from the given string.
What I can't figure out is what I'm doing wrong to cause this, if you're curious about what sqlite system I'm using, you can find the home page here: http://www.zentus.com/sqlitejdbc/
Thanks in advance for any help on this. I'm completely stumped.
Note: In an attempt to save resources, I was caching my Connection's, and re-using them later. When I try re-getting the connection, it works perfectly. Is there a way I can cache them or do I need to load them every time I want to use it?
I was getting this error, and it was caused because I had closed the connection. The connection wasn't null, it was just closed. ARRRGGG! Like the OP hinted at, I had started with the sample code at Zentus (Xerial now, since Zentus seems to have shut down). The sample code has a finally block where he closes the connection. Once I took out the finally block, my error disappeared. Just remember to close the connection before you exit the program.
To see if you have the same problem, right before the line that gives the error, try adding
System.out.println("isClosed = " + conn.isClosed());
If not wrong, I think it is because of ';' inside your SQL statement. Please remove and try again ?
Regards,
Code Behind

Categories

Resources