I'm trying to call the query:
UPDATE questions
SET 1 = 4
WHERE questionid = 4;
But I keep receiving an SQL syntax error. I have a column in my table called '1', and I want to set that columns value to the integer 4. I tried some other queries(below), but I still the same error.
UPDATE questions
SET '1' = 4
WHERE questionid = 4;
UPDATE questions
SET '1' = 4
WHERE 'questionid' = 4;
UPDATE questions
SET "1" = 4
WHERE questionid = 4;
UPDATE questions
SET "1" = 4
WHERE "questionid" = 4;
I'm trying to perform this query in java using the executeUpdate() method from the Statement java API.
I know some of you would advise me using a PerformedStatement rather than a regular Statement for building queries, and I will do, once I can figure out why my query isn't accepting that 1 is a column name and not an integer.
Use backticks arround the column name:
UPDATE questions
SET `1` = 4
WHERE questionid = 4;
Think about renaming your column.
Try the following:
UPDATE questions
SET [1] = 2 -- int
WHERE QuestionID = 1;
Related
Using Java I want to obtain all IDs from my database and select GW_STATUS if it is equal to 0. I used the following SQL statement to achieve this.
PreparedStatement get_id = con.prepareStatement("SELECT ID from SF_MESSAGES where GW_STATUS = 0");
Once the IDs have been obtained, I want to update GW_STATUS to 1 according to their ID as demonstrated in the code below but only one field is being updated when I execute the code.
PreparedStatement update = con.prepareStatement("update SF_MESSAGES set GW_STATUS=? where ID = ?");
update.setInt(1,1);
ResultSet x = get_id.executeQuery();
while(x.next()){
int uber = x.getInt(1);
int array[] = new int[] {uber};
for (int value : array) {
System.out.println("Value = " + value); //Successfully obtains and prints each ID from the databse table
update.setInt(2,value); // Only one ID is updated therefore only field updated
}
}
int result = update.executeUpdate();
System.out.println(result + " Records updated");
I've tried using another update statement within the for loop to update every ID obtained but that doesn't work too. How can I successfully update every field according to their ID?
You can make the whole processing much simple. It turns out that you just want to update SF_MESSAGES which have GW_STATUS equals to 0, so your query can look like the following:
update SF_MESSAGES set GW_STATUS=1 where GW_STATUS=0
Therefore, you do not have to fetch IDs, loop over them so it is more efficient solution.
I have 2 ResultSets. 1st ResultSet contains the records from table1 from database1 and 2nd ResultSet contains the records from table2 from database2. I need a list of records from resultset1 which are not present in resultSet2. For this I wrote this logic but it is not working and throwing me the following error.
java.sql.SQLException: Invalid operation for read only resultset: deleteRow
if ( table1ResultSet != null )
{
while ( table1ResultSet.next() )
{
final String table1Record = table1ResultSet.getString( 1 );
if ( table2ResultSet != null )
{
while ( table2ResultSet.next() )
{
final String table2Record = table2ResultSet.getString( 1 );
if ( table1Record.toString().equalsIgnoreCase( table2Record.toString() ) )
{
table1ResultSet.deleteRow();
break;
}
}
}
}
}
return table1ResultSet;
That exception says what the problem is - your result set doesn't support delete. In order to have updateable result set there are some requirements:
When you prepare statement did you make it with ResultSet.CONCUR_UPDATABLE?
A query can select from only a single table without any join operations.
The query must select all non-nullable columns and all columns that do not have a default value. A query cannot use "SELECT * ". Cannot select derived columns or aggregates such as the SUM or MAX of a set of columns.
You might want to move the results sets into Java sets before working doing what you are doing though because using deleteRow will actually delete the row from the database (unless that's the expected result)
There is another problem with your code though. Even if delete works your code will fail on the second iteration of result set 1 because you never reset table2ResultSet and for the second iteration there won't be more results in table2resulset.
But on top of all that. Why would you go through all that hussle and get all that rows that you don't need instead of doing it with one single query like:
select * from table 1 where id not in select id from table 2
or
delete from table 1 where id not in select id from table 2
if that's the goal
Your logic:
Assumes the records come in some order (which may or may not be true, depending on your SQL)
Consumes the entire result set 2 for each row of result set 1, which is unlikely your intent
Deletes things, which is also not what you mentioned in the question
Your question can be implemented easily as such:
Set<String> list1 = new HashSet<>();
while (table1ResultSet.next())
list1.add(table1ResultSet.getString(1).toLowerCase());
while (table2ResultSet.next())
list1.remove(table2ResultSet.getString(1).toLowerCase());
System.out.println(list1);
This will print all the values (without duplicates) that are present in the first result set, but not in the second.
I'm using MySQL and fetching a few different values from a table and then perform some basic math on it. Currently three seperate SELECT statements are in use and afterwards I perform some simple addition and subtraction with the outputs I get in Java.
I'm trying to optimize my code but sadly I gotta admit I'm a complete SQL noob. I'm pretty sure there's a way to join these select querys and the calculations so that I actually only get one output but I've not been able to find it.
My table looks something like this:
ID | value | inc | timestamp
--------------------------------------
0 | 5 | 4 | 2018-02-01 10:28:21
1 | 8 | 3 | 2018-02-01 10:28:47
...
My code currently looks like this:
int maxValue = MySQL.executeQuery("SELECT MAX(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())");
int minValue = MySQL.executeQuery("SELECT MIN(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())");
int minInc = MySQL.executeQuery("SELECT `inc` FROM `table` where ID = id AND value = minValue");
int output = maxValue - minValue + minInc;
Is there a way to shorten it to a single
int output = MYSQL.executeQuery( ??? );
?
Simply do select (select ...) - (select ...) + (select ...)
In your case, you can do( not tested in real environment )
select (SELECT MAX(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())) - ( SELECT MIN(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())) + (SELECT `inc` FROM `table` where ID = id AND value = minValue)
First off, there's something funky going on with the maxValue and minValue selects. The Max() and Min() operators will give you the max and min values of a given column of a given set of rows. Using one of these operators with such a specific where (by what seems to be a table's primary key) is probably not what you want to be doing.
Now, answering your question, I think you could do something along the lines of:
SELECT MAX('value') as max, MIN('value') as min
FROM `table` as t
WHERE ...
to "join" (careful with this word) the first 2 queries. This is simple select syntax: usually, there's no problem with selecting more than a column or an aggregate function at a time. Or, something like:
SELECT `inc`
FROM `table`
WHERE ID = id AND
value = (SELECT MIN('value') FROM 'table' WHERE ...)
to "join" the last two.
Single statement is possible using INNER JOIN since you are using a single able. Try this
SELECT MAX(`a.value`)-(MIN(`a.value`)+b.`inc`) AS Output
FROM `table` a
INNER JOIN `table` b ON a.ID=b.ID
AND a.ID = idvalue AND `a.timestamp` >= TIMESTAMPADD(a.DAY,-3,NOW())
AND b.value=(select MIN(value) from table WHERE ID=id);
I am using two identical JPQL NamedQueries, except that one is a COUNT. Here are the queries:
select i from IssueRingReqsBrit i where i.ringDataRequest = 'I' and i.onRingIssue = 'Y' and i.noCardIssued = 0
select COUNT(i) from IssueRingReqsBrit i where i.ringDataRequest = 'I' and i.onRingIssue = 'Y' and i.noCardIssued = 0
IssueRingReqsBrit is a view.
The first query is returning a list of 6, which is correct.
The second query, the count, return 0.
Databased being used is Oracle. Using Glassfish with Eclipselink. Shared cache mode on the PU is set to none.
Using native queries in Oracle, the correct values are returned.
Below is the code I use to execute the queries, and check the results. There is no other code between these lines, they were copy and pasted as they are in the Java.
query = em.createNamedQuery("IssueRingReqsBrit.onRingIssue_toSend_initial");
System.out.println("Size: " + query.getResultList().size() );
//ringingRequestRingIssueYesToSendInitial
query = em.createNamedQuery("IssueRingReqsBrit.onRingIssue_toSend_initial_count");
ringingRequestRingIssueYesToSendInitial = ((Long)query.getSingleResult()).intValue();
System.out.println("ringingRequestRingIssueYesToSendInitial = " + ringingRequestRingIssueYesToSendInitial);
Any suggestions are appreciated.
Based on the JPQL Language reference, in the COUNT function, the path expression that is the argument to the aggregate function must terminate in a state-field. The path expression argument to COUNT may terminate in either a state-field or a association-field, or the argument to COUNT may be an identification variable. So try something like this
select COUNT(i.<field>) from IssueRingReqsBrit i where i.ringDataRequest = 'I' and i.onRingIssue = 'Y' and i.noCardIssued = 0
COUNT returns Long.
Make use you are returning the resulat in a Long.
I am using Hibernate and want to query multiple entities using a composite index (a,b,c,d). The SQL statement could look like this:
SELECT *
FROM my_table
WHERE a = 2 AND b = '2001' AND c = 'xx' AND d = 23
OR a = 2 AND b = '2002' AND c = 'xx' AND d = 23
-- OR ...
;
Is there a chance to pass hibernate just a list for such a query? What I don't want is to use a StringBuffer to concatenate a statement depending on the length of my list.
Criterai it´s the best for this tutorial
I hope help you