SQLite functions using PreparedStatement - java

How to use SQLite function using PreparedStatement?
PreparedStatement stmt;
String query = "insert into Test values(?,?)";
stmt = conection.prepareStatement(query);
stmt.setString(2, "date('now')");
date('now') is the SQLite function I want to use, but it inserts "date('now')" as Text..

One way of achieving this is by changing your sql string, with this you may not need to set the date parameter anymore in your preparedstatement.
String query = "insert into Test values(?,date('now'))";
Now just you need to set the parameter 1
stmt.setString(1, <<param1 value>>);

Related

Dynamic variable in executeUpdate (Java)

I have the following connection, statement and executeUpdate
Connection con = DBConnPool.getInstance().getConnection();
Statement stmt = con.createStatement();
//String str1 = "update node set compareflag=0, personalid=NULL where ipaddress='192.168.150.213'";
String str1 = "update node set compareflag=0, personalid=NULL where ipaddress='var3.getIpAddress()'";
stmt.executeUpdate(str1);
The commented out String line works perfectly, the other one ignores the value returned by var3.getIpAddress() even though that variable does contain the correct data which I use in other areas of my code.
Do I have to create a separate variable first and then equate it to var3.getIpAddress() ?
Any thoughts appreciated, it's probably insufficient " or " in the wrong place.
Prefer a PreparedStatement with a bind parameter. Dynamically building a query leaves you vulnerable to SQL Injection attacks. PreparedStatement (when used correctly) is immune to SQL Injection. It also makes the code easier to read and reason about. For example,
Connection con = DBConnPool.getInstance().getConnection();
String qry = "update node set compareflag=0, personalid=NULL where ipaddress=?";
PreparedStatement stmt = con.prepareStatement(qry);
stmt.setString(1, var3.getIpAddress());
stmt.executeUpdate();
You should use PreparedStatement to set parameter for safe.
PreparedStatement pstmt = con.prepareStatement("update node set compareflag=0, personalid=NULL where ipaddress=?");
pstmt.setString(1,var3.getIpAddress());
pstmt.executeUpdate();

Java Preparedstatement error when reading from MySql Database

I'm working on a simple application that pulls data from a local database. The below code works fine when I use a string for the SQL query, but I can not get it to work with PreparedStatement. I have reviewed similar problems posted here but most of those were caused by doing this, preparedStmt.executeQuery(query); instead of this preparedStmt.executeQuery(); Here is the code,
private final String POSTTITLE= "posttitle"; // DB Column name
private final String POSTCONTENT= "content"; // DB Column name
public String getDbContent(){
try{
String query ="select values(?, ?) from blog";
PreparedStatement preparedStmt = this.connect.prepareStatement(query);
preparedStmt.setString (1,POSTTITLE);
preparedStmt.setString (2,POSTCONTENT);
ResultSet rs = preparedStmt.executeQuery();
rs.next();
return(rs.getString(this.POSTCONTENT)); //Will replace with loop to get all content
} catch(Exception e) {
System.err.println("Error Reading database!");
System.err.println(e);
return("Error: "+e);
}
}
This is the error I get:
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 ''posttitle', 'content') from blog' at line 1
Parameters in prepared statements are for values - you're trying to use them to select fields. They just don't work that way.
In this very specific instance, you'll need to make the SQL dynamic. However, you'll want to make sure that whatever code you have to allow your columns to be specified is tightly constrained to avoid SQL injection attacks. (For example, you could have an enum with the columns in, or a whitelist of allowed values.)
Try concatenating select query:
String query ="select "+POSTTITLE+","+POSTCONTENT+" from blog";
Remember that prepared statements are for values, not query parameters, for them we use simply concatenations.
Try this:
String query ="select POSTTITLE, POSTCONTENT from blog";
PreparedStatement preparedStmt = this.connect.prepareStatement(query);
ResultSet rs = preparedStmt.executeQuery();
rs.next();
There is no need to use field names as parameter.

Java PreparedStatement Comment on Table

I'm familiar with using java prepared statements to insert/update on a table. In oracle you can add a comment on a table, how would I use a preparedstatement to do that?
This was my initial attempt with no luck;
PreparedStatement stmt = con.prepareStatement("comment on table my_table is q'[?]'");
stmt.setString(1, description);
stmt.executeUpdate();
You can use system Oracle table and set comment there with PreparedStatement, like this:
PreparedStatement stmt = con.prepareStatement(
"UPDATE user_tab_comments SET comments = ? WHERE table_name = 'my_table'");
Or try to use simple statement:
String commentOnTableSQL = String.format("COMMENT ON TABLE my_table is '%s'", comment);
Statement statement = dbConnection.createStatement();
statement.execute(commentOnTableSQL);

Using PrepareStatement to get data with configurable table name

I'm trying to get some data from Oracle 11.2 using java and jdbc driver.
My goal is to get data from database using CallableStatement, but with no luck - I'm not able to put table name as parameter. I would like to have configurable table name in query. However, it would be good to keep it sanitized.
Here is an example..
public void getData() throws SQLException {
Connection conn = Config.getSQLConnection();
String query = "SELECT * FROM ?";
PreparedStatement st = conn.prepareStatement(query);
st.setString(1, Config.DATATABLE_NAME);
ResultSet rs = st.executeQuery();
if (rs.next()) {
System.out.println("SUCCESS");
System.out.println("ID:" + rs.getString("ID"));
} else {
System.out.println("FAILURE");
}
}
Is this the way it should work? Or am I missing something, or misused it?
A CallableStatement is used to make call to stored procedures.
From javadoc:
The interface used to execute SQL stored procedures
Use a PreparedStament instead for a normal select.
As an additional note don't pass the name of the table as parameter.
Create the query using concatenation.
Instead of
String query = "SELECT * FROM ?";
use
String query = "SELECT * FROM " + Config.DATATABLE_NAME;
You should use PreparedStatement instead of CallableStatement.
CallableStatement is an interface which is used to call stored procedures.

Oracle :SQL command not properly ended

String req="INSERT INTO NOTIFICATIONS VALUES(6,1,sysdate,'toz',02542,'bporp')(SELECT valide from mouvement where valide=?)";
I want to make a request with Conditions but I get the error:
SQL command not properly ended
You have an invalid SQL query. Here's your current SQL statement:
INSERT INTO NOTIFICATIONS VALUES(6,1,sysdate,'toz',02542,'bporp')(SELECT valide from mouvement where valide=?)
If we split this into several lines for better understanding, you will have this:
INSERT INTO NOTIFICATIONS
VALUES(6,1,sysdate,'toz',02542,'bporp')
(SELECT valide from mouvement where valide=?)
Which is not a valid statement, not even for any SQL tool. That's because you have 2 statements without separating them: an INSERT and then a SELECT, and you're not executing an INSERT INTO <TABLE1> SELECT ... FROM <TABLE2>.
You should execute a single SQL statement per Statement or PreparedStatement. This, in Java, should be done like this:
String sql1 = "INSERT INTO NOTIFICATIONS"
+ " VALUES(6,1,sysdate,'toz',02542,'bporp')";
String sql2 = "SELECT valide from mouvement where valide=?";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql1);
PreparedStatement pstmt = con.prepareStatement(sql2);
pstmt.setString(1, <parameter_value>);
ResultSet rs = pstmt.executeQuery();

Categories

Resources