Dynamic variable in executeUpdate (Java) - 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();

Related

Executing multiple queries with single PS

i have created prepared statement object .
now i want to get the result of multiple queries . is it possible to do using single prepared statement object/ find the piece code below
PreparedStatement ps = null;
String moviedirectorQry = "SELECT movie_director FROM movies WHERE movie_title= ?";
ps = dbConnection.prepareStatement(moviedirectorQry);
ps.setString(1, "Twilight");
ResultSet rs=null;
rs = ps.executeQuery(moviedirectorQry);
while (rs.next()) {
String director_name = rs.getString("movie_director");
System.out.println("director name : " + director_name);
}
now i want to run another query.. how to do
If the idea is to use the same PreparedStatement for different queries of the same type with only parameters' value that change, yes it is possible, simply call clearParameters() first to clear the parameters in case you want to reuse it before setting the new parameters' value.
The code could be something like that:
if (ps == null) {
// The PreparedStatement has not yet been initialized so we create it
String moviedirectorQry = "SELECT movie_director FROM movies WHERE movie_title= ?";
ps = dbConnection.prepareStatement(moviedirectorQry);
} else {
// The PreparedStatement has already been initialized so we clear the parameters' value
ps.clearParameters();
}
ps.setString(1, someValue);
ResultSet rs = ps.executeQuery();
NB: You are supposed to use executeQuery() not ps.executeQuery(moviedirectorQry) otherwise the provided parameters' value will be ignored such that the query will fail.

SQLite functions using PreparedStatement

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

why we use setInt with select query instead of using getInt when value is already there in database

why we use setInt with select query instead of using getInt when value is already there in database?
try {
conn = getConnection();
ps = conn.prepareStatement("SELECT * FROM circle where id =?");
ps.setInt(1, circleId);
Circle circle = null;
rs = ps.executeQuery();
if (rs.next()) {
//String s = rs.getString(circleId);
circle = new Circle(circleId, rs.getString("name"));
}
You're setting the value of the parameter to be used in the query. The ? in the SQL represents the parameter, and here you're giving it a value.
When you call getString() later, that's getting a value from the results of the query, which are very different from the parameters sent as part of the query.
Parameterized SQL allows safe inclusion of values into queries, without needing to escape them to prevent SQL injection attacks, or worrying about data type conversions. You should read the JDBC PreparedStatement tutorial for more details.

How to assign a Value taken from the database to a label?

I need to assign a string taken by a query from the database to a Jlabel. I tried many methods but failed. How can i do it?
try{
String sql="SELECT MAX(allocationID) FROM allocation where unit='"+ dept + " ' ";
pst=conn.prepareStatement(sql);
String x= (pst.execute());
}
catch(Exception e){
}
Need to study the steps to connect to the database in java First db steps
Get the resultset from the statment by calling ResultSet rs = pst.execute();
Iterate through the list of rows by using the resultset object.
After that assign the value to the JLabel.
You just made several errors in your tiny program, take a look at the code below as an example:
// your way of using prepared statement is wrong.
// use like this
String sql="SELECT MAX(allocationID) FROM allocation where unit=?;";
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
// assign values to the variables in the query string
ps.setString(1, dept);
// execute the query
ResultSet rst = ps.executeQuery();
// parse the result set to get the value
// You'd better do some check here to ensure you get the right result
rst.next();
String x = rst.getInt(1) + "";
ps.close();
conn.close();
}
Have a look at the article if you are interested:https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html

Java + MySQL - PreparedStatement troubles with encoding

I got this program that interacts with MySQL. It works but acts strangely when non-ASCII occur in the statement. I'm using prepared statement:
public ResultSet executeQuery(Connection _conn, int _val1, String _val2) throws SQLException {
PreparedStatement stmt = _conn.prepareStatement("SELECT c.name FROM categories c,languages l WHERE c.language = l.id AND c.user = ? AND l.name = ?;");
stmt.setInt(1, _val1);
stmt.setString(2, _val2);
return stmt.executeQuery();
}
It works fine unless I use something like "čččč" in _val2. Problem is somewhere in Java because when I prepare the statement a print it to stdout those characters are just "????". Any suggestions?
Try adding characterEncoding=UTF-8 parameter to the end of your JDBC connection URL. Even set the table and column character set to UTF-8. This article explains how to do that.

Categories

Resources