Suppose I have a Querystring defined as follows:
String MyTableCount = "SELECT"
+ "COUNT(*) AS TOTALCOUNT "
+ " FROM "
// and so on
How do I access the "TOTALCOUNT" value as I want to compare it's value to another value?
I was thinking something like the following:
if((MyTableCount.TOTALCOUNT) > 100 )
{
}
else
{
}
But this generates an error, as TOTALCOUNT variable needs to be defined.
You need to print out the query string. According to what you have, it starts as:
SELECTCOUNT(*) AS TOTALCOUNT
This is not a recognized SQL command. You need a space after the SELECT.
Related
So I gather tweets from twitter using Twitter4j, add each one to a list named statuses, and then check each statuses text for the word "the" using an if statement and contains. If true, it adds one to a counter and then at the end, displays the counter, but the counter always says 0 even if the was in the tweet. code is as follows:
for (Status status : statuses) {
String fullTweet = ((follower.getScreenName() + " - " + status.getCreatedAt() + " - " + status.getText()).replaceAll("\\n", "").replaceAll("\\r", ""));
System.out.println(fullTweet);
if (fullTweet.toLowerCase().contains("the")) {
the = the++;
}
}
Write your increment as the += 1 instead of the = the++, or simply the++.
You're assigning the value before the increment, since having ++ after the variable is a post increment.
This question already has answers here:
How to insert values in a table with dynamic columns Jdbc/Mysql
(2 answers)
Closed 5 years ago.
What is a good design pattern to achieve this without endless code?
Given the scenario whereby the user may input 1...100 columns, maybe 23 one time, 32 on another insert, and 99 fields on another insert etc. All of which may be different fields each time too.
The PreparedStatement in Java needs to know what column names to enter first, how many ?'s to put into the values part of the INSERT query, the data types of the database field names to ensure the correct setInt and setString etc are entered.
For less than around 10 columns, you can kind of get around this challenge with the following logic;
1) If variableEnteredForFieldName is not null, then append to the relevant parts of the query in the form of a String builder type setup;
fieldName_1
?
2) Do the same for all entered field names
3) Strip out the final trailing , that will naturally be present in both the field names and the ?s
4) Create the PreparedStatement
5) Run through the same input parameters again to determine of the variableEnteredForFieldName is not null, if not null, then run a setInt or setString based on the known data type that the database requires and set this to the correct index number for the ?s.
As long as the query builder logic and the query filler logic have the names/values in the correct order in part 1 and part 2, then all works well. It does however mean duplicating the entire code that relates to this logic, one for generating the SQL to use when creating the PreparedStatement and another for filling the PreparedStatement.
This is manageable for a small number of input parameters, but this soon gets unmanageable for larger number of input parameters.
Is there a better design pattern to achieve the same logic?
The code below is an outline of all of the above for reference;
String fieldName1 = request.getParameter("fieldName1");
String fieldName2 = request.getParameter("fieldName2");
//Build Query
String fieldNames = "";
String fieldQuestionMarks = "";
if (fieldName1 != null) {
fieldNames = fieldNames + " FIELD_NAME_1 ,";
fieldQuestionMarks = fieldQuestionMarks + " ? ,";
}
if (fieldName2 != null) {
fieldNames = fieldNames + " FIELD_NAME_2 ,";
fieldQuestionMarks = fieldQuestionMarks + " ? ,";
}
//Trim the trailing ,
fieldNames = fieldNames.substring(1, fieldNames.length() - 1);
fieldQuestionMarks = fieldQuestionMarks.substring(1, fieldQuestionMarks.length() - 1);
try {
String completeCreateQuery = "INSERT INTO TABLE_NAME ( " + fieldNames + " ) VALUES ( " + fieldQuestionMarks + " );";
Connection con = DriverManager.getConnection(connectionURL, user, password);
PreparedStatement preparedStatement = con.prepareStatement(completeCreateQuery);
int parameterIndex = 1;
//Fill Query
if (fieldName1 != null) {
preparedStatement.setString(parameterIndex, fieldName1);
parameterIndex++;
}
if (fieldName2 != null) {
preparedStatement.setInt(parameterIndex, Integer.parseInt(fieldName2));
parameterIndex++;
}
}
As you can see, it's do-able. But even with just 2 optional fields, this code is huge.
The way I see it, if user is able to omit any of the columns from the list, then all columns are optional, and can be safely set to NULL during an insert. Therefore, all you need is one prepared statement with the "monster" INSERT, with all columns listed; then during the actual insert operation, you loop though the user-provided data, setting values for the columns provided, and calling setNull() for omitted columns. You'll need to maintain a structure somewhere (your DAO class most likely) mapping column names to their order in the SQL statement.
Individual ind = model.createIndividual("http://www.semanticweb.org/ontologies/Word#Human", isSynonymOf);
System.out.println( "Synonyms of given instance are:" );
StmtIterator it =ind.listProperties(isSynonymOf);
while( it.hasNext() ) {
Statement stmt = ((StmtIterator) it).nextStatement();
System.out.println( " * "+stmt.getObject());
}
Output
Synonyms of given instance are:
http://www.semanticweb.org/ontologies/Word#Human
http://www.semanticweb.org//ontologies/Word#Mortal
http://www.semanticweb.org/ontologies/Word#Person
Problem 1: My output shows whole URI but I need output as under
Synonyms of given instance are:
Human
Mortal
Person
Problem 2: I have 26 instances and every time I have to mention its URI to show its synonyms. How will I show synonyms of any instance from whole ontology model instead of mentioning URIs again and again. I am using eclipse Mars 2.0 and Jena API
You can use REGEX or simply Java string operations to extract the substring after #. Note, best practice is to provide human readable representations of URIs and not to encode it in the URI. For instance, rdfs:label is a common property for doing that.
It is simply iterating over all individuals of the ontology which are returned by
model.listIndividuals()
Some comments:
You're using the method createIndividual not as expected. The second argument denotes a class and you're giving it a property. Please use Javadoc for the future.
I don't understand why you're casting it to StmtIterator - that doesn't make sense
Using listPropertiesValues is more convenient since you're only interested in the values.
Use Java 8 to make the code more compact
model.listIndividuals().forEachRemaining(ind -> {
System.out.println("Synonyms of instance " + ind + " are:");
ind.listPropertyValues(isSynonymOf).forEachRemaining(val -> {
System.out.println(" * " + val);
});
});
Java 6 compatible version:
ExtendedIterator<Individual> indIter = model.listIndividuals();
while(indIter.hasNext()) {
Individual ind = indIter.next();
System.out.println("Synonyms of instance " + ind + " are:");
NodeIterator valueIter = ind.listPropertyValues(isSynonymOf);
while(valueIter.hasNext()) {
RDFNode val = valueIter.next();
System.out.println(" * " + val);
}
}
I have a java program that connects to a database and I'm trying to update something in the database using prepared statements and parameterized queries. Here is part my code :
updateValSetId = con.prepareStatement("UPDATE COLUMNNAME " +
"SET COLUMNDISPLAYNAME = ? + ' Value Set Identifier' " +
"WHERE COLUMNDISPLAYNAME = ? + 'VALSETID' and TABLENAME = ?");
the first couple values I'm putting in for the question mark arguments are 1- Account, 2- ACCT, the third one doesn't matter. MY QUESTION IS---> is there any way to combine the question mark to a string value? the addition sign doesn't work I get the error " ORA=01722: invalid number "
after I looked up what that error meant I changed my code to something like this :
updateValSetId = con.prepareStatement("UPDATE COLUMNNAME " +
"SET COLUMNDISPLAYNAME = '? Value Set Identifier' " +
"WHERE COLUMNDISPLAYNAME = '?VALSETID' and TABLENAME = ?");
that didn't work either. So again is there any way to combine the question marks with strings?
Thanks!
EDIT----------> I decided to take out the string text after the ? and put it in a different spot:
updateValSetId.setString(1, f.getValue() + " Value Set Identifier");
updateValSetId.setString(2, f.getKey() + "VALSETID");
updateValSetId.setString(3, e.getKey());
updateValSetId.executeUpdate();
This is after my prepared statements, when I'm assigning the values to the ? parameter. the 'f' and the 'e' are hashmaps that I have data stored in, and I'm wondering why the above code doesn't work either when I add the string to the value i get from getValue and getKey. I don't get any errors, it compiles and runs but it doesn't update the values I want it to in the database. For example, ACCT is the first key and Account is the first value, so when they get passed in they should end up being added to the string I have after the getters, and therefore the database should update ACCTVALSETID to Account Value Set Identifier, right? What am I missing?
Thanks!
The edit I made is actually correct, I had errors in other parts of my code, the following code works:
updateValSetId.setString(1, f.getValue() + " Value Set Identifier");
updateValSetId.setString(2, f.getKey() + "VALSETID");
updateValSetId.setString(3, e.getKey());
updateValSetId.executeUpdate();
So I guess you can't add string values to the ? parameter, but this works exactly the same as if you were adding it to the ?
I have a simple model involving title and description. It extends play.db.jpa.Model
The following search method works perfectly
public static SearchResults search(String search, Integer page) {
String likeSearch = "%" + search + "%";
long count = find("title like ? OR description like ? order by " +
"title ASC", likeSearch, likeSearch).fetch().size();
List<Must> items = find("title like ? OR description like ? order by " +
"title ASC", likeSearch, likeSearch).fetch(page, 20);
return new SearchResults(items, count);
}
However when I tweak count as follows
long count = count("title like ? OR description like ? order by " +
"title ASC", likeSearch, likeSearch);
I get
PersistenceException occured :
org.hibernate.exception.SQLGrammarException: could not execute query
ERROR ~ ERROR: column "must0_.title" must appear in the GROUP BY
clause or be used in an aggregate function
Why is the error asking me to use an aggregate function when the query has not changed at all?
This is because in the first query, all the records are returned and then counted in the result list.
In your second query the count is done in the database so your sql must be formed correctly.
I think the order by is causing the error you described, try removing it. You are trying to order on column which are not part of the return (count return numbers not columns).
You can set the jpa.debugSQL=true in your application.conf if you need to see the sql generated.