Sqlite reading text with apostrophe - java

I have a sqlite database which contains strings. I am reading those strings from my javafx interface. Everything is working smoothly, however my problem is when I am trying to read strings with apostrophe. My code for reading the strings is the following:
String sql = "select * from Questions where Subject = ? and Grade = ? and Level = ? and questionId = ?";
PreparedStatement pst = gui.connectionQuestions.prepareStatement(sql);
pst.setString(1,gui.textSubjectQTest);
pst.setString(2,gui.showGradeLabel.getText());
pst.setString(3,gui.showCurrentLevelLabel.getText())
pst.setString(4,list.get(counter));
ResultSet rs = pst.executeQuery();
if(rs.next())
{
String temp = rs.getString("Question");
gui.question.setText(temp);
...
sql = "Update Questions set Used ='"+1+"' where Question = '"+gui.question.getText().replaceAll("'", "/'")+"'";
pst = gui.connectionQuestions.prepareStatement(sql);
pst.execute();
In the above code I peform a query to return the question string and add it to a label gui.question. However due to the apostrophe I am receiving the following error (I got the error due to the last line):
[SQLITE_ERROR] SQL error or missing database (near "(": syntax error)
I tried to follow the solution from here, however my prob still remains. How can I solve the thing with the apostrophe?
EDIT: I tried to escape character using double apostrophe. This approach is working but it changes my string to double apostrophe, which is not useful.

The quote or apostrophe character is escaped by doubling it.
BTW You don't need the if (temp.contains("'")).

Related

How to import text longer than String from JTextArea into TEXT field in database

I have a problem with this for a while. Importing data from TEXT field into textArea make no problem for me (even if it's longer than String), but I have no idea how to make it work opposite way. (Using sqlite)
My code to get data from db:
Statement myStmt = con.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * from test");
while(myRs.next())
{
if(myRs.getInt("Id_przepisu") == przepis.getId_przepisu() )
{
textArea.setText(myRs.getString("text"));
}
}
myStmt.close();
myRs.close();
code to save data in db
insert = con.prepareStatement
( "INSERT INTO test (Id_przepisu, text) VALUES ('"+przepis.getId_przepisu()+"','"+
textArea.getText()+"')");
insert.executeUpdate();
You might find a good answer and workaround for you problem here: https://stackoverflow.com/a/17785119/575643
In short, if is bigger than the TEXT type you would need to split it manually. Search for substring, it would help.

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException Insert mysql error

This is the whole message I receive:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user','age','school','password') values ('Admin','22','tei','admin')' at line 1
And this is the code:
String user = textField.getText().trim();
String age = textField_3.getText().trim();
String school = textField_4.getText().trim();
String password = String.valueOf(passwordField.getPassword());
String password1 = String.valueOf(passwordField_1.getPassword());
if(password.equals(password1)){
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","1234");
PreparedStatement st = con.prepareStatement("insert into user ('user','age','school','password') values ('"+user+"','"+age+"','"+school+"','"+password+"')");
int rs = st.executeUpdate();
JOptionPane.showMessageDialog(frame, "Data Saved Successfully");
Any ideas?
The point of prepared statements is, among others, to not concatenate your queries yourself.
You want to do the following:
//first you "prepare" your statement (where the '?' acts as a kind of placeholder)
PreparedStatement st = con.prepareStatement("insert into user (user,age,school,password) values (?,?,?,?);");
//now you bind the data to your parameters
st.setString(1, user);
...
//and then you can execute it
st.executeUpdate()
For more details see the official tutorial.
There are a couple of things happening behind the scenes that make the query safe, like escaping special characters that would otherwise allow altering the statement (google SQL injections if you want to know more)

Writing multiple where clauses in Java using Mysql

below is code is a code i wrote to get the value of 'monthly Depreciation' when i select the row on my j Table by either mouse-clicked or key-pressed. but it only selects the first value for 'monthly depreciation' when i click on the rows or key-press.the problem i know is coming from the where statement but can't seem to get around it.
if(evt.getKeyCode()==KeyEvent.VK_DOWN || evt.getKeyCode()==KeyEvent.VK_UP)
{
try{
int row =dep_report.getSelectedRow();
String Table_click=(dep_report.getModel().getValueAt(row, 0).toString());
String sql ="select Date_Acquired 'Date Acquired',Serial_Number 'Serial Number',"
+ " Description 'Description',Cost_Of_Acquisition 'Cost Of Acquisition',"
+ "Monthly_Depreciation 'Monthly Depreciation',Accumulated_Depreciation 'Accumulated Depreciation',Net_Book_Value 'Net Book Value'"
+ ",asset_update.Branch_Area 'Branch Area',Depts_name 'Department Name' ,User 'User',"
+ "Status 'Status' from items,asset_update where items.items_No = asset_update.items_No &&'"+Table_click+"'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()){
String add1 = rs.getString("Monthly Depreciation");
MonthlyDep.setText(add1);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
I would really appreciate the help thank you.
In your sql
where items.items_No = asset_update.items_No &&'"+Table_click+"'";
&& wont work for sql and you might need
where items.items_No = asset_update.items_No and items.someThing= '"+Table_click+"'";
Please use Java naming conventions and give proper names to things Table_click is a horrible variable name.
But can you describe what is in your table model in the 1st column of the selected row?
You seem to append that to your query and if it does not contain a valid SQL part, this will not work well with your statement. In a where clause you usually check a column against a value. I doubt that your table model has this written there, more likely you just have the value in your table model at this position.
Also make sure to properly use prepared statements. Never put the values directly in the SQL string you create or you create the perfect entry point for SQL injection. Assign the values instead once you have created the statement with something like this: pst.setString(1, Table_click);

Where's my invalid character (ORA-00911)

I'm trying to insert CLOBs into a database (see related question). I can't quite figure out what's wrong. I have a list of about 85 clobs I want to insert into a table. Even when inserting only the first clob I get ORA-00911: invalid character. I can't figure out how to get the statement out of the PreparedStatement before it executes, so I can't be 100% certain that it's right, but if I got it right, then it should look exactly like this:
insert all
into domo_queries values ('select
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = ''CHQ PeopleSoft FS''')
select * from dual;
Ultimately, this insert all statement would have a lot of into's, which is why I just don't do a regular insert statement. I don't see an invalid character in there, do you? (Oh, and that code above runs fine when I run it in my sql developer tool.) And I if I remove the semi-colon in the PreparedStatement, it throws an ORA-00933: SQL command not properly ended error.
In any case, here's my code for executing the query (and the values of the variables for the example above).
public ResultSet executeQuery(String connection, String query, QueryParameter... params) throws DataException, SQLException {
// query at this point = "insert all
//into domo_queries values (?)
//select * from dual;"
Connection conn = ConnectionPool.getInstance().get(connection);
PreparedStatement pstmt = conn.prepareStatement(query);
for (int i = 1; i <= params.length; i++) {
QueryParameter param = params[i - 1];
switch (param.getType()) { //The type in the example is QueryParameter.CLOB
case QueryParameter.CLOB:
Clob clob = CLOB.createTemporary(conn, false, oracle.sql.CLOB.DURATION_SESSION);
clob.setString(i, "'" + param.getValue() + "'");
//the value of param.getValue() at this point is:
/*
* select
* substr(to_char(max_data),1,4) as year,
* substr(to_char(max_data),5,6) as month,
* max_data
* from dss_fin_user.acq_dashboard_src_load_success
* where source = ''CHQ PeopleSoft FS''
*/
pstmt.setClob(i, clob);
break;
case QueryParameter.STRING:
pstmt.setString(i, "'" + param.getValue() + "'");
break;
}
}
ResultSet rs = pstmt.executeQuery(); //Obviously, this is where the error is thrown
conn.commit();
ConnectionPool.getInstance().release(conn);
return rs;
}
Is there anything I'm just missing big time?
If you use the string literal exactly as you have shown us, the problem is the ; character at the end. You may not include that in the query string in the JDBC calls.
As you are inserting only a single row, a regular INSERT should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):
String query1 = "select substr(to_char(max_data),1,4) as year, " +
"substr(to_char(max_data),5,6) as month, max_data " +
"from dss_fin_user.acq_dashboard_src_load_success " +
"where source = 'CHQ PeopleSoft FS'";
String query2 = ".....";
String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();
reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();
pstmt.executeBatch();
con.commit();
Of the top of my head, can you try to use the 'q' operator for the string literal
something like
insert all
into domo_queries values (q'[select
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;
Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.
One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .
Oracle provide some explanation for ORA-00911. You can got this explanation after executing SQL request in Oracle SQL Developer.
ORA-00911. 00000 - "invalid character"
*Cause: identifiers may not start with any ASCII character other than
letters and numbers. $#_ are also allowed after the first
character. Identifiers enclosed by doublequotes may contain
any character other than a doublequote. Alternative quotes
(q'#...#') cannot use spaces, tabs, or carriage returns as
delimiters. For all other contexts, consult the SQL Language
Reference Manual
But in your case it seems to be double ' character

concat sequence next value with string

i want the sequence next value to be inserted into table after concatenating with some string value. eg: case12. Here 'case' will be the string and '12' will be the next sequence value.
i'm trying this code in my jsp page.
String name=request.getParameter("name").toString();
String pwd=request.getParameter("pass").toString();
out.print(name+" and "+pwd);
String add="case";
PreparedStatement ps = connect.prepareStatement("insert into test(caseid,userid,pass) values('CONCAT('"+add+"',test_seq.nextval)',?,?)");
ps.setString(1,name);
ps.setString(2,pwd);
ps.executeUpdate();
connect.commit();
connect.close();
but, i'm getting this error java.sql.SQLException: ORA-00917: missing comma
can anybody tell me the solution for above problem. Any help appreciated.!!
If at all possible, you should prefer passing in parameters to dynamically assembling a SQL statement. So if you don't want "case" to be a hard-coded constant, it ought to be a bind variable.
Additionally, you don't want single-quotes around the CONCAT call. Something like this should work.
String name=request.getParameter("name").toString();
String pwd=request.getParameter("pass").toString();
out.print(name+" and "+pwd);
String add="case";
String sqlStmt = "insert into test(caseid,userid,pass) values(CONCAT(?,test_seq.nextval),?,?)";
PreparedStatement ps = connect.prepareStatement(sqlStmt);
ps.setString(1,add);
ps.setString(2,name);
ps.setString(3,pwd);
ps.executeUpdate();
connect.commit();
connect.close();

Categories