I want to convert below java Statement into PreparedStatement combining 2 parameters i.e. input1 and input2. How to do that?
public static void main(String[] args) {
String input1="Hello";
String input2="World";
try {
String sql = "select * from veracodetable where output = \'" +input1 + input2+ "\'";
statement = con.createStatement();
statement.executeQuery(sql);
rs = s.getResultSet();
}
catch (Exception e) {
}
}
Something like this?
String sql = "select * from veracodetable where output = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(input1+input2);
statement.executeQuery();
rs = s.getResultSet();
Of course the PreparedStatement would have just one parameter, as you can see.
Related
public List<StateGalleryAdListing> getGalleryListing(String state, String category) throws SQLException {
List<StateGalleryAdListing> adListingList = new ArrayList<>();
try{
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM stateGalleryListingList WHERE state =" + state + "AND category = " + category;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
StateGalleryAdListing GalleryAdListing = new StateGalleryAdListing();
GalleryAdListing.setState(rs.getString(1));
GalleryAdListing.setCategory(rs.getString(2));
GalleryAdListing.setAdLink(rs.getString(3));
GalleryAdListing.setImageHeaderTxt(rs.getString(4));
GalleryAdListing.setImageSrc(rs.getString(5));
adListingList.add(GalleryAdListing);
}
} catch(SQLException ex) {
ex.getSQLState();
}
return adListingList;
}
I've also tried to use a PreparedStatment:
String sql = "SELECT * FROM stateGalleryListingList Where state = ? AND category = ?";
PreparedStatement stmt = conn.conn.prepareStatement(sql);
stmt.setString(1, state);
stmt.setString(2, category);
ResultSet rs = stmt.executeQuery();
this route still doesn't work, and when I look the error I'm not seeing anything useful. Thanks in advance for any useful advice!
my issue was here:
ResultSet rs = stmt.executeQuery(sql);
I didn't need to pass sql into the executeQuery() method. Thanks for your help though guys.
I want to use two sql query in my java code. the first query retain all row of table2 and the second one get it's rows one by one. I wrote follow code but it face to "This ResultSet is closed, it means rs ResultSet " error. How can I fix?
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
ResultSet rsWithin = stmt.executeQuery(sqlWithin);
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}
You need to create separate PreparedStatement object for inner query
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
PreparedStatement preparedStatement = null;
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
preparedStatement = dbConnection.prepareStatement(sqlWithin);
ResultSet rsWithin = preparedStatement.executeQuery();
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}
The function below will pick the highest value and it will display value which are in column place1(in table placeseen) as output based on the ID.So far I only can get the highest value but not the value in place1.
I don't know what's wrong with my coding because the output is always shows empty.
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0+1];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
String sql ="Select* from placeseen where ID =aa[i]";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
ps.close();
rs.close();
conn.close();
}
}
System.out.println(highest);
}
instead of
String sql ="Select * from placeseen where ID =aa[i]";//aa[i] taking a value
use
String sql ="Select place1 from placeseen where ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]);
passing aa[i] variable value .
Avoid sql injection
You can try this
// as you are using preparedStatement you can use ? and then set value for it to prevent sql injection
String sql = "Select * from placeseen where ID = ?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]); // 1 represent first attribute represented by ?
System.out.println(ps); // this will print query in console
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println("Inside rs.next()"); // for debug purpose
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
// remaining code
I am just trying to insert a new row in a table from a java application to an SQL database. I have used the same code before and it worked but for some reasons this doesn't. I have checked my query by inserting it directly in phpmyadmin and it works. Here is my code:
where I actually try to sent the query:
static Connection conn = MySQLAccess.connectDB();
static PreparedStatement pst = null;
static ResultSet rs = null;
public static String submit(String usrn, String psw){
String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
try {
pst = conn.prepareStatement(sql);
System.out.println(sql);
rs=pst.executeQuery();
if (rs.next()){
return "ok";
} else {
return "fail";
}
} catch (Exception e){
return "fail_connection";
}
}
MySQLAccess.java (which I am sure works because I use is at other points in the code):
public class MySQLAccess {
Connection conn=null;
public static Connection connectDB (){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/g52gui","root","");
return conn;
}catch(Exception e){
return null;
}
}
}
I have just changed my code (suggestion of Luiggi Mendoza) but no result:
public static String submit(String usrn, String psw){
//String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
String sql = "INSERT INTO tbl_user VALUES('', '?', '?')";
String result = "failed";
try (Connection conn = MySQLAccess.connectDB();
PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, usrn);
pst.setString(2, psw);
pst.executeUpdate();
result = "worked";
} catch (SQLException e) {
//handle your exception...
}
return result;
}
Three issues:
Use PreparedStatement#executeUpdate rather than PreparedStatement#executeQuery.
Keep the variables in the narrowest possible scope. Don't set them as static variables in your class.
Don't concatenate the parameters into the query string. Instead, use PreparedStatement#setXyz method to set the proper parameter.
Gluing all of these together produces the following code:
public static String submit(String usrn, String psw){
//String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
String sql = "INSERT INTO tbl_user VALUES('', ?, ?)";
String result = "failed";
try (Connection conn = MySQLAccess.connectDB();
PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, usrn);
pst.setString(2, psw);
pst.executeUpdate();
result = "worked";
} catch (SQLException e) {
//handle your exception...
}
return result;
}
From your new code, the problem is here:
String sql = "INSERT INTO tbl_user VALUES('', '?', '?')";
^ ^ ^ ^
You're wrapping the parameter character ? with quotes '. Remove such quotes, as shown in my code:
String sql = "INSERT INTO tbl_user VALUES('', ?, ?)";
//No quotes around ?
You should use executeUpdate and not executeQuery;
I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();
String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();
public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}