How to pass java string variable in sql query .I have done all the JDBC connection .
My sql database query is
sql = \"Select *
from productio
Whenever I have to make sql queries I use a library like jdbi to do it. This will allow you to create an interface with different queries. All you have to do is define the interface, create a POJO, and create a mapper between a SQL table and a Java POJO.
The interface would look something like this.
@RegisterMapper(ProductionMapper.class)
public interface ProductionDAO {
@SqlQuery("Select * from production AS cust INNER JOIN location AS comp ON cust.location_id = comp.location_id where comp.name = :name AND crop_id =1")
Production findRow(@Bind("name") String name);
}
The POJO would look something like this.
public class Production {
private VariableTypeA variableA;
// other variables
public Production(VariableTypeA variableA ....) {
this.variableA = variableA;
// set everything else
}
// getters and setters
}
The mapper would look something like this.
public class ProductionMapper implements ResultSetMapper {
public Production map(int index, ResultSet r, StatementContext ctx) throws SQLException {
return new Production(r.getSomeType("columnName"), ...);
}
}
This design makes it really simple to interact with your database and pass variables as well as making it so that your classes dont violate the SRP
http://jdbi.org/sql_object_overview/