hello mates hope you having a nice day, i have a really weird problem with getting data from Mysql database in Java , in the method here :
ResultSet tableExistence;
.
.
.
while (tableExistence.next()) {
System.out.println("before : "+tableExistence.getInt(MyHttpServer.COL_ID));
if(tableExistence.getString(MyHttpServer.COL_STATUS).equals(MyHttpServer.STATUS_AVAILABLE)){
System.out.println("after : "+tableExistence.getInt(MyHttpServer.COL_ID));
...
}
weirdly the value of the "before" is for the right value of the id , but after the if method, the value of "after" returns some thing like 1234125151231 , any idea why is this problem ?!!!!
The ResultSet documentation states:
The docs do say "For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once."
So technically, it's somewhat reasonable. However:
I would actually expect that any modern, well-supported database would allow you to access the columns in an arbitrary order, multiple times
Just returning an incorrect value rather than throwing an exception to indicate the problem is pretty nasty
One explanation could be if you're fetching a clob or blob - the driver may decide in that case that "left to right only" is more reasonable, to avoid having to keep too much data in memory. It's still not great that it just returns corrupted data though.
So while this is a possible answer, I would also:
Check that neither the connection nor the ResultSet is being used from multiple threads concurrently
Check that you're using a recent version of the MySQL driver
Related
I don't have much code to post, and I'm quite confused on where to start. There's a lot of documentation online and I can't seem to find what I'm looking for.
Suppose I have this query result saved into a StatementResult variable:
result = session.run("MATCH (n:person {tag1: 'Person1'})"
+ "RETURN [(n)-->(b) WHERE b:type1 | m.tag2]")
In the Neo4j browser, this returns a list of exactly what I'm looking for. My question is how we can access this in Java. I know how to access single values, but not a list of this type.
Any help would be appreciated.
Thanks.
Usually you just iterate over the statement results, to access each record and then with each record you can access each named column. You didn't use any names.
The column will return Value objects which you then can turn into the types you expect, so in your case into a list with asList().
See the API docs for StatementResult and Value.asList()
also your statement is not correct you probably meant b where you wrote m and you need to name your column to access it
I am trying to insert NULL value for my NUMBER column in H2 database.
In my Java model the corresponding value is Long (not primitive). Now, I am aware how JDBC driver inserts 0 for nulls if not specified, but I do exactly that.
My DAO layer is in Spring, and for this exact column I am mapping its value in this manner.
if(user.getDefaultNumber() == null){
map.addValue("defaultNumber", user.getDefaultNumber(), Types.NULL);
}else{
map.addValue("defaultNumber", user.getDefaultNumber());
}
However, this does not seem to be working. I have tracked it deep into Spring Core classes, and null value for my object is there, but somewhere it still gets turned to 0.
Can someone please help me, this is bugging me for days.
Please try PreparedStatement to save null value in integer column
pst.setNull(4, java.sql.Types.INTEGER);
enter link description here
The solution to the problem was adding Types.Integer. I am still not sure why it did not work with Types.NULL but I will investigate. For now this is the solution
if(user.getDefaultNumber() == null){
map.addValue("defaultNumber", user.getDefaultNumber(), Types.INTEGER);
}else{
map.addValue("defaultNumber", user.getDefaultNumber());
}
Also, it is very important to map it properly when reading from DB. JDBC will read NULLs from database, but it will still insert 0 in Java's attribute. So, if reading is not handled properly as well, it might leave an impression that the problem persists even though the writing part is actually OK.
If "FirstName" and index 1 refer to the same column in a query, and rs is a ResultSet, why would
if(rs.getString("FirstName")!=null) fullName = rs.getString("FirstName");
and
if(rs.getString(1)!=null) fullName = rs.getString(1);
behave differently?
According to the Java docs, using either the columnIndex or the columnLabel
both return the value of the designated column.
I'm running into a weird problem when I use the columnIndex instead of the columnLabel, for some reason, after the jsp has been running for a few hours/days then if(rs.getString(1)!=null) evaluates to true even when the String is null. When I use the columnLabel instead, the problem doesn't happen. Can anyone tell me why this might be happening?
Extra background info
The program runs in Tomcat. We updated Tomcat, the JVM, and our database driver on the same day, and this started happening. If we reload the app in Tomcat, it starts working correctly, at least for a few hours. We switched back to the old database driver and the problem continues, so we have ruled out the database driver.
rs.getString(1) returns the data for the first column in your SQL query executed (by the preparedStatement), it need NOT be the FirstName, you need to cross check that your SQL query in preparedStatement is as follows:
SELECT FirstName from X;//you might add where conditions
From your comment:
it just starts returning the String "null" instead of the actual null value. So the fullName becomes the String "null".
In other words the problem is different from what is stated in your question. null and "null" aren't the same thing, so there is no reason for rs.getString(1) == null to return true if the actual value is "null".
I would say you probably have "null" in your database somewhere. Check. Or else you are using String.valueOf(null) somewhere in your code, possibly indirectly, e.g. via println(null), which calls it, so the output is "null".
We have solved it. We decided to try a different SQL driver (we were using a Microsoft driver before, we switched to JTDS) and all problems have gone away.
So I'm guessing the Microsoft driver was returning the string "null" when it should have been returning null.
So to answer the question, the ResultSet.getString() method was probably behaving correctly all along, but the SQL driver was returning bad data.
I feel like I'm missing something very obvious here, but it seems that the only way to go about doing this is to get the value, and then see if it returns a null (empty) value, which I would rather not do.
Is there an equivalent to List.contains(Object o) in SQL? Or perhaps the JDBC has something of that nature? If so, what is it?
I am using Microsoft Access 2013.
Unfortunately I don't have any useful code to show, but here is the gist of what I am trying to do. It isn't anything unique at all. I want to have a method (Java) that returns the values of a user that are stored in the database. If the user has not previously been added to the database, the user should be added, and the default values of the user should be set. Then those newly created values will be returned. If a player has already been added to the database (with the username as the primary key), I don't want to overwrite the data that is already there.
I would also advise against using MS Access for this purpose, but if you are familiar with MS Office applications, the familiar UI/UX structure might help you get your footing and require less time to learn other database environments. However, MS Access tends to be quite limited, and I would advise considering alternative options if available.
The only way to see if an SQL table contains a row with some condition on a column is to actually make an SQL query. I don't see why you wouldn't do that. Just make sure that you have an index on the column that you will be constraining the results on. Also for better speed use count to prevent from retrieving all the data from the rows.
SELECT count(*) FROM foos WHERE bar = 'baz'
Assuming you have an index on the bar column this query should be pretty fast and all you have to do is check whether it returns > 0. If it does then you have rows matching your criteria.
You can use "IF EXISTS" which returns a boolean value of 1 or 0.
select
if(
exists( select * from date1 where current_date()>now() ),
'today > now',
'today is not > now'
) as 'today > now ?' ;
+--------------------+
| today > now? |
+--------------------+
| today is not > now |
+--------------------+
1 row in set (0.00 sec)
Another Example:
SELECT IF(
EXISTS( SELECT col from tbl where id='n' ),
colX, colY
) AS 'result'
FROM TBL;
I'm also new to sql and I'm using Oracle.
In Oracle, suppose we have: TYPE: value.
We can use:
where value not in (select TYPE from table)
to make sure value not exist in the column TYPE of the table.
Don't know if it helps.
You can simply use Query with condition.
For example if you have to check records with particular coloumn, you can use where condition
select * from table where column1 = 'checkvalue'
You can use count property to check the no. of records existing with your specified conditon
select count(*) from table where column1 = 'checkvalue'
I have created the following method, which to my knowledge works perfectly. (Using the java.sql package)
public static containsUser(String username)
{
//connection is the Connection object used to connect to my Access database.
Statement statement = this.connection.createStatement();
//"Users" is the name of the table, "Username" is the primary key.
String sql = "SELECT * FROM Users WHERE Username = '" + username + "'";
Result result = statement.executeQuery(sql);
//There is no need for a loop because the primary key is unique.
return result.next();
}
It's an extremely simple and extremely basic method, but hopefully it might help someone in the future.
If there is anything wrong with it, please let me know. I don't want anyone learning from or using poorly written code.
IMPORTANT EDIT: It is now over half a decade after I wrote the above content (both question and answer), and I now advise against the solution I illustrated above.
While it does work, it prioritizes a "Java-mindset-friendly" approach to SQL. In short, it is typically a bad idea to migrate paradigms and mindsets of one language to another, as it is inevitable that you will eventually find yourself trying to fit a square peg into a round hole. The only way to make that work is to shave the corners off the square. The peg will then of course fit, but as you can imagine, starting with a circle peg in the first place would have been the better, cleaner, and less messy solution.
Instead, refer to the above upvoted answers for a more realistic, enterprise-friendly solution to this problem, especially as I imagine the people reading this are likely in a similar situation as I was when I originally wrote this.
So I have a MYSQL db in which boolean values are stored as binary(1). I was to investigate why certain queries were slow even though there was an index on the relevant columns. The issue was that when building the SELECT query, the system was using the setBoolean method of PreparedStatement which, as I understand it, converts the value to MYSQL TINYINT. The query found the correct rows, but never used the index since the index was on a binary column. However, if I instead used the setString method and converted the boolean to a string, namely '0' for false and '1' for true, MYSQL was able to use the index and find the wanted rows fast.
Basically, the first query is what I got when using setBoolean and the second when using setString:
SELECT someColumn FROM table WHERE binaryColumn = 1 //Does not use index
SELECT someColumn FROM table WHERE binaryColumn = '1'//Uses index
In Java the change was this:
PreparedStatement ps1 = ...
ps1.setBoolean(1, true);
...
PreparedStatement ps2 = ...
ps2.setString(1, "1");
...
My question is simply if there is a better way to do this? Everything works fine but for some reason I think the code "smells" but I cant really motivate why.
I prefer always the setBoolean, because of abstraction.
The real interesting point is when your DB uses the index.
The optimizier of the DB use a index only, if it makes sense. If you have 1000 entries and a booleanvalue only split it into 50/50 it make no sense for that index, especial when its not the PK - but if you use a additional limitation, to get only 10 rows, as result, a good optimizer should use the index you specified - maybe a "composed index" on 2 columns (booleanColumn1, StringColumn1)
MySQL uses TINYINT(1) for the SQL BOOL/BOOLEAN. So I would change the data type to BOOLEAN, in accordance to standard SQL.
By your relay, the issue should then be resolved. By the way BIT(1) would be another option.