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 '' at line 1
my code:
public static void loanenquiry(String ApplicationID,String LoanNumber,String RIMNumber,String custname,String fromdate,String todate) {
String wherestring = "SELECT * FROM bf_loanmaster WHERE";
try {
if(ApplicationID != null) {
wherestring = wherestring + "ApplicationID ="+BillAction.StringtoInt(ApplicationID)+"";
}
if(LoanNumber != null ) {
if(ApplicationID != null) {
wherestring = wherestring + "AND LoanNumber = "+BillAction.StringtoInt(LoanNumber)+" ";
} else {
wherestring = wherestring + "LoanNumber = "+BillAction.StringtoInt(LoanNumber)+" ";
}
}
if(RIMNumber != null ) {
if(ApplicationID != null && LoanNumber != null) {
wherestring = wherestring + "AND AdvparyRIM = "+RIMNumber+" ";
} else {
wherestring = wherestring + "AdvparyRIM = "+RIMNumber+"";
}
}
if(custname != null ){
if(ApplicationID != null && LoanNumber != null && RIMNumber != null ) {
wherestring = wherestring + "AND custName = "+custname+"";
} else {
wherestring = wherestring + "custName = "+custname+"";
}
}
if(fromdate != null ) {
if(ApplicationID != null && LoanNumber != null && RIMNumber != null && custname != null ) {
wherestring = wherestring + "AND ApplicationDt >= "+BillAction.StringtoDate(fromdate)+" ";
} else {
wherestring = wherestring + "ApplicationDt = "+BillAction.StringtoDate(fromdate)+"";
}
}
if(todate != null ) {
if(ApplicationID != null && LoanNumber != null && RIMNumber != null && custname != null && fromdate != null) {
wherestring = wherestring + "AND ApplicationDt >= "+BillAction.StringtoDate(fromdate)+" AND ApplicationDt <= "+BillAction.StringtoDate(todate)+"";
} else {
wherestring = wherestring + "ApplicationDt >= "+BillAction.StringtoDate(todate)+"";
}
}
Connection conn = BillFinanceDB.getDBConnection();
PreparedStatement psloanenquiry= conn.prepareStatement(wherestring + ";");
ResultSet rs = psloanenquiry.executeQuery();
while(rs.next()) {
System.out.println("loan number"+rs.getInt("LoanNumber"));
}
} catch(SQLException e) {
e.printStackTrace();
}
}
Any ideas?
thanks for the help.
My guess: you're missing a space after WHERE in your constructed string. Try this:
String wherestring = "SELECT * FROM bf_loanmaster WHERE ";
The best way to debug these kinds of errors is to print out the SQL query you have constructed before it is executed so that you can manually inspect it for problems.
The WHERE is most likely a problem. The second problem that you could have is not putting your strings in quotation marks. For example it probably should be wherestring = wherestring + "custName = '"+custname+"' ";
Also things to note:
All this appending is terribly inefficient, use a StringBuilder or StringBuffer instead. You could also use PreparedStatements which would make your code perform better and possibly even make it easier to read.
Add a space after where.. You have to seperate keywords like where..
give a space in your query
String wherestring = "SELECT * FROM bf_loanmaster WHERE";
there is no space between WHERE statement and condition.
Related
I have to rewrite some code, but couldn't find proper information on the Internet. The original part looks like this:
String query = "select * from sublog_type_map_v where 1 = 1";
if (responsibleGroupId != null && responsibleGroupId.length() != 0 && !responsibleGroupId.equals("0")) {
query += " and responsible_group_id = " + responsibleGroupId;
}
if (categoryId != null && categoryId.length() != 0 && !categoryId.equals("0")) {
query += " and category_id = " + categoryId;
}
if (typeId != null && typeId.length() != 0 && !typeId.equals("0")) {
query += " and type_id = " + typeId;
}
if (subtypeId != null && subtypeId.length() != 0 && !subtypeId.equals("0")) {
query += " and subtype_id = " + subtypeId;
}
And I've proceeded to this code:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<SublogTypeMapV> query = builder.createQuery(SublogTypeMapV.class);
Root<SublogTypeMapV> root = query.from(SublogTypeMapV.class);
query.select(root).where(builder.equal(root.get("responsibleGroupId"), responsibleGroupId));
But this "where" should be considered optional using "if" expression, as well as the other three parameters (which I will add later). I have no earthly idea how to do it, could anyone help me out?
I guess this will do the needful -
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<SublogTypeMapV> query = builder.createQuery(SublogTypeMapV.class);
Root<SublogTypeMapV> root = query.from(SublogTypeMapV.class);
query = query.select(root);
if("some boolean expression") {
query = query.where(builder.equal(root.get("responsibleGroupId"), responsibleGroupId));
}
Similarily you can handle other conditions inside.
I don't understand why in this code, it's do that:
query.setString("idFamilleDeProduit", String.valueOf(familleDeProduits.getFamilleDeProduitsGenerique().getId()));
When I looked my table in my database, id column is integer.
it's PostgreSql-9.4.1207
my function:
public List<ContratMdd> recherchePourDuplication(String typeAccord, FamilleDeProduitsNomenclature familleDeProduits, SocieteInterne societeInterne, SocieteExterne societeExterne, String anneeAccord) throws PersistenceException {
List<ContratMdd> listContratMdd = new ArrayList<ContratMdd>();
String requete = "";
if (!"".equals(anneeAccord)){
requete += " anneeAccord = :anneeAccord";
}
if (!"".equals(typeAccord) && ! "".equals(requete)){
requete += " AND";
}
if (!"".equals(typeAccord)){
requete += " type = :type";
}
boolean existFamille = false;
requete += (familleDeProduits != null && familleDeProduits.getFamilleDeProduitsGenerique() != null) ? " AND " : "";
if(familleDeProduits != null && familleDeProduits.getFamilleDeProduitsGenerique() != null){
existFamille = true;
requete += " estAppliqueSur.familleDeProduitsGenerique IS NOT NULL AND estAppliqueSur.familleDeProduitsGenerique.id = :idFamilleDeProduit";
}
boolean existSocieteInterne = false;
boolean existSocieteExterne = false;
requete += (societeInterne != null) ? " AND " : "";
if(societeInterne != null){
existSocieteInterne = true;
String table = societeInterne instanceof Master ? "MasterImpl" : "AdherentImpl";
requete += " contractantInterne.id = :idsocieteInterne AND contractantInterne IN (FROM "+table+") ";
}
requete += (societeExterne != null) ? " AND " : "";
if(societeExterne!=null){
existSocieteExterne = true;
String table = societeExterne instanceof GroupeIndustriel ? "GroupeIndustrielImpl" : "FournisseurImpl";
requete += " contractantExterne.id = :idsocieteExterne AND contractantExterne IN (FROM "+table+") ";
}
if (!"".equals(requete)) {
requete = "from ContratMddImpl where" + requete;
Query query = createQuery(requete);
if (!"".equals(anneeAccord)){
query.setBigInteger("anneeAccord", new BigInteger(anneeAccord));
}
if (!"".equals(typeAccord)){
query.setString("type", typeAccord);
}
if(existFamille){
query.setString("idFamilleDeProduit", String.valueOf(familleDeProduits.getFamilleDeProduitsGenerique().getId()));
}
if (existSocieteInterne){
query.setInteger("idsocieteInterne", societeInterne.getId());
}
if (existSocieteExterne){
query.setInteger("idsocieteExterne", societeExterne.getId());
}
listContratMdd.addAll((List<ContratMdd>) query.list());
}
return listContratMdd;
}
It is happening because the Postgre's DB Driver allows it. But you should be using setInt() instead of setString() for an Integer as other DB Drivers might not support it.
Here is what java.sql.PreparedStatement Documentation has to say:
Note: The setter methods (setShort, setString, and so on) for setting
IN parameter values must specify types that are compatible with the
defined SQL type of the input parameter. For instance, if the IN
parameter has SQL type INTEGER, then the method setInt should be used.
Hi I'm trying to filter records on the basis of Brand,Flavor,Price,Size,Type. i am using a single form to handle this so if user filter only by brand then rest of options like price,flavor will be unchecked so i am checking if Brand or flavor or price is null.I got the solution but i have make lot of comparisons for all cases. i need a solution by which i have make less comparisons.I am using following code
public List<Products> Filter_Items(String[] Brand, String[] Flavour,Float Price,String Size,String Type)
{
ResultSet rs;
List<Products> data = null;
PreparedStatement stmt;
try {
StringBuilder param = new StringBuilder();
if (Brand != null) {
for (String str : Brand) {
param.append("'").append(str).append("', ");
}
}
StringBuilder param1 = new StringBuilder();
if (Flavour != null) {
for (String str : Flavour) {
param1.append("'").append(str).append("', ");
}
}
String prm = param.toString().length() > 2 ? param.toString()
.substring(0, param.toString().length() - 2) : null;
String prm1 = param1.toString().length() > 2 ? param1.toString()
.substring(0, param1.toString().length() - 2) : null;
String query = "select * from products where ";
if (prm != null && prm1 != null) {
query += "Brand in (" + prm + ") and Flavour in (" + prm1 + ")";
} else if (prm != null && prm1 == null) {
query += "Brand in (" + prm + ")";
} else if (prm1 != null && prm == null) {
query += "Flavour in (" + prm1 + ")";
}
stmt = DataBaseConnection.DBConn.getConnection().prepareStatement(query);
rs = stmt.executeQuery();
if (rs != null) {
data = new ArrayList<Products>();
while (rs.next()) {
Products p = new Products();
p.setTitle(rs.getString("Ttile"));
p.setCategory(rs.getString("Category"));
p.setSubCategory(rs.getString("SubCategory"));
p.setSubCategoryTwo(rs.getString("SubCategorytwo"));
p.setPrice(rs.getInt("Price"));
p.setFlavour(rs.getString("Flavour"));
p.setSize(rs.getString("Size"));
p.setImage(rs.getString("image"));
p.setBrand(rs.getString("Brand"));
p.setInstock(rs.getString("instock"));
p.setInstockQty(rs.getInt("instockqty"));
data.add(p);
}
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
return null;
}
return data;
}
}
You can use as always third party libraries for validation like javax validation or any other more specialized on this.
You could create a bean of your data with all the getters and setters and apply validation on your bean.
To pass arrays you need getters and setters like this one:
public class Foo {
private int[] array;
public Foo(int[] array) {
this.array = Arrays.copyOf(array, array.length);
}
/** #param the array to use */
public setArray(int[] array) {
this.array = Arrays.copyOf(array, array.length);
}
/** #return a copy of the array */
public int[] getArray() {
return Arrays.copyOf(array, array.length);
}
}
To validate a bean see this tutorial.
What you really need is to start naming variables according to what they are logically. Names like prm and prm1 are meaningless, while brand and flavor make more sense as variable names since that's what's in them.
I don't see the number of comparisons as a problem. But giving everything generic variable names and then not even indenting the if-statements makes my eyes glaze over.
How about something like this:
if (brand != null && flavor != null)
{
query += "Brand in (" + brand + ") and Flavour in (" + flavor + ")";
}
else if (brand != null && flavor == null)
{
query += "Brand in (" + brand + ")";
}
else if (flavor != null && brand == null)
{
query += "Flavour in (" + flavor + ")";
}
Edit: One thing you can do is split your SQL into two variables, one for the main query and one for the where clause, then just add to the where clause like this:
private String addToWhereClause(String currentWhereClause, String fieldname, String value)
{
String returnValue = "";
if (value != null)
{
if(!"".equals(currentWhereClause))
{
returnValue += " AND ";
}
returnValue += " "+fieldname+" IN(" + value + ") ";
}
return returnValue;
}
String whereClause = "";
whereClause += addToWhereClause(whereClause, "Brand", brand);
whereClause += addToWhereClause(whereClause, "Flavour", flavor);
query = query + " " + whereClause;
I have a constants file abcder.constants as shown below
public static final String ABC_abbject_EOD = "DDD_Report";
public static final String CDE_abbject_INTRADAY = "FFD_Report";
Now I have the below method as shown below
public void Gen(String[] toAddress, String[] ccAddress, String abbject,
String message, String defIdentifier, Date date)
Now in this method there can be two cases that is either defIdentifier is null or abbject parameter has a value
So if defIdentifier is null then abbject has a value which is coming from a abcderconstant so in that case I have to do something. That is depending upon the value of the abject it can be ABC_abbject_EOD or CDE_abbject_INTRADAY
If defIdentifier is not null then abbject is null then in that case I have to perform some other thing
So, I have developed the code as shown below please advise is this correct way
if (defIdentifier != null && abbject== null)
{
String s = defIdentifier + "-" + formatter.format(now.getTime()) + "." + "doc";
}
if (defIdentifier == null && abbject.equalsIgnoreCase(abcderconstants.ABC_abbject_EOD))
{
String s = "DDD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}
if (defIdentifier == null && abbject.equalsIgnoreCase(abcderconstants.CDE_abbject_INTRADAY))
{
String s = "FFD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}
StringBuilder sb = new StringBuilder();
if (defIdentifier != null && abbject == null) {
sb.append(defIdentifier);
} else if (defIdentifier == null && abbject != null ) {
if(abbject.equalsIgnoreCase(abcderconstants.ABC_abbject_EOD)) {
sb.append("DDD-Report");
} else if (abbject.equalsIgnoreCase(abcderconstants.CDE_abbject_INTRADAY)) {
sb.append("FFD-Report");
} else {
// throw invalid abbject type exception?
}
} else {
// both defIdentifier and abbject are either null or not null. Illegal args?
}
sb.append("-" + formatter.format(now.getTime()) + "." + "doc");
String s = sb.toString();
Put String s = ... outside the if statements. It may be a good idea to check if abbject is null. Please try to use better variable names.
String s = null;
if (defIdentifier != null && abbject == null) {
s = defIdentifier + "-" + formatter.format(now.getTime()) + "." + "doc";
}
else if (defIdentifier == null && abbject != null && abbject.equalsIgnoreCase(abcderconstants.ABC_abbject_EOD)) {
s = "DDD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}
else if (defIdentifier == null && abbject != null && abbject.equalsIgnoreCase(abcderconstants.CDE_abbject_INTRADAY)) {
s = "FFD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}
So I have this code that checks 4 parameters (author, title, keyword and subject) to do some dynamic sql query generation for a project I'm working on and I was just wondering if anyone knew of a better way to write this out. I get the feeling this is a really inefficient way to do this but it's late and I'm tired. Please let me know if you know of any better way to do this, it's just a bunch of if/else case checking statements at this point.
Thanks!
if(_author!=null)
{
query += authorQ;
if(_title != null)
{
if(conjunct[0] == 0)
{
query += " AND ";
query += titleQ;
}
else
{
query += " OR ";
query += titleQ;
}
if(_keyword != null)
{
if(conjunct[1] == 0)
{
query += " AND ";
query += keywordQ;
}
else
{
query += " OR ";
query += keywordQ;
}
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
else
{
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
}//title = null
else
{
if(_keyword != null)
{
if(conjunct[1] == 0)
{
query += " AND ";
query += keywordQ;
}
else
{
query += " OR ";
query += keywordQ;
}
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
else //keyword null
{
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
//if subject's null at this point we don't care
}
}
}
else //author null
{
if(_title != null)
{
if(conjunct[0] == 0)
{
query += " AND ";
query += titleQ;
}
else
{
query += " OR ";
query += titleQ;
}
if(_keyword != null)
{
if(conjunct[1] == 0)
{
query += " AND ";
query += keywordQ;
}
else
{
query += " OR ";
query += keywordQ;
}
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
else
{
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
}//title = null
else
{
if(_keyword != null)
{
if(conjunct[1] == 0)
{
query += " AND ";
query += keywordQ;
}
else
{
query += " OR ";
query += keywordQ;
}
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
}
else //keyword null
{
if(_subject != null)
{
if(conjunct[2] == 0)
{
query += " AND ";
query += subjectQ;
}
else
{
query += " OR ";
query += subjectQ;
}
}
//if subject's null at this point we don't care
}
}
}
How about a more structured and scalable approach, see example below. By the way, you shouldn't really be putting user input straight into SQL queries - use prepared statements instead to try to guard against injection attacks.
// test values
String _author = "authorfoo";
String _title = "titlebar";
String _keyword = null;
String _subject = "subjectfoo";
String authorQ = "author=" + _author;
String subjectQ = "subject=" + _subject;
String titleQ = "title="+ _title;
String keywordQ = "keyword=" + _keyword;
int conjunct[] = new int[]{ 0, 1, 1, 0};
// query building code
String []inputs = {_author, _title, _keyword, _subject};
String []queries = {authorQ, titleQ, keywordQ, subjectQ};
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < inputs.length; i++) {
if (inputs[i] != null) {
if (builder.length() > 0) { // don't start query with connective
if (conjunct[i] == 0) {
builder.append(" AND ");
} else {
builder.append(" OR ");
}
}
builder.append(queries[i]);
}
}
String query = builder.toString();
System.out.println(query);
a = _author ? authorQ : 1;
t = _title ? titleQ : 1;
k = _keyword ? keywordQ : 1;
s = _subject ? subjectQ : 1;
c1 = conjunct[0] ? " OR " : " AND ";
c2 = conjunct[1] ? " OR " : " AND ";
c3 = conjunct[2] ? " OR " : " AND ";
query += a + c1 + t + c2 + k + c3 + s;