I need to know what the number X needs to be in order to receive the data properly.
Example code :
Statement sta = (connection object).createStatement();
sta.executeQuery("SELECT 'points' FROM TABLEX WHERE 'player'='" + player_name + "'").getString(X); ///HERE
Either 1, or "points" will work.
1 is the index of the column as specified in the select statement. The indexing starts from 1 and increments from there.
Otherwise the name of the column may be used, in this case "points". That method may cause a bit more meta data to get loaded and so performance can vary.
As the javadoc says :
getString(int columnIndex)
Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. and
getString(String columnLabel)
Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.
So this is not going to work. It will give you :
java.sql.SQLException: Before start of result set
First of all you need to iterate through the Resultset obtained using next() then you can retrieve the specific values by either pass 1 which is the column index in this case or points which is the columnName of your table and based on the where clause it shall give you different values of the column points
X is the column number(index) in the table.
It is needed to fetch the data from table.
You also can use column name instead of column index like this -
getString(ColumnName);
Related
I found a SQL query in some Java code that looks like this:
SELECT * FROM tableA JOIN tableB ON ...
Both tableA and tableB contain the field named id, and the Java code that executes this query does this:
Integer id = (Integer)rs.getObject("id");
Does the JDBC spec have anything to say about which field value will be returned? I haven't been able to find anything that says one way or another. I see that some databases throw an error but MySQL/MariaDB (the database in use, here) do not complain and the value returned seems to be tableA.id, or the "leftmost" field whose name is "id".
I'm asking if there is spec-defined behavior in this case, or if it's up to the database and/or JDBC driver to decide how to behave.
Needless to say, I'll be fixing this to work predictably and unambiguously while I'm looking at the code, but I'm curious as to the answer.
The API documentation of ResultSet answers your question:
Column names used as input to getter methods are case insensitive.
When a getter method is called with a column name and several columns
have the same name, the value of the first matching column will be
returned.
The JDBC 4.3 specification document in section 15.2.3 Retrieving Values also says:
The columns are numbered from left to right, as they appear in the
select list of the query, starting at 1.
Column labels supplied to getter methods are case insensitive. If a
select list contains the same column more than once, the first
instance of the column will be returned.
The index of the first instance of a column label can be retrieved
using the method findColumn. If the specified column is not found,
the method findColumn throws an SQLException.
So, if a result set has multiple columns with the same (case insensitive(!)) name, then the value of the first matching column is returned.
I am trying to batch updates using PreparedStatement where the data you get in varies in what you have available.
Simple example:
You have a table with column x and y. Your inputdata is a representation of rows where only the modified column is present. So for row 1 you have x='foo' and for row 2 you have y='bar'. In order to batch these with a PreparedStatement you need one SQL statement: "update table where x=?,y=? where etc".
The solution that I am working towards is setting the column where you dont have any value to the value that is already present, but I'm not sure if this is possible. In raw SQL you could write "update table where x=x and y='foo' where etc", however I haven't found any ways to achieve this by setting the "?" parameter to be a reference to the column, it seems it's not possible.
Is it possible to handle this case at all with PreparedStatements? I apologize if my explanation is poor.
Assuming the values you want to set are all non-null, you could use a statement like
update sometable set column1 = coalesce(?, column1), colum2 = coalesce(?, column2)
Then when the value should not be updated, use either PreparedStatement.setNull with an appropriate java.sql.Types value or a PreparedStatement.setXXX of the appropriate type with a null as value.
As discussed in the comments, an alternative if you do need to update to null, is to use a custom function with a sentinel value (either for updating to null or for using the current value). Something like:
update sometable set column1 = conditional_update(?, column1), colum2 = conditional_update(?, column2)
Where conditional_update would be something like (using Firebird 3 PSQL syntax):
create function conditional_update(new_value varchar(500), original_value varchar(500))
returns varchar(500)
as
begin
if (new_value = '$$NO_UPDATE$$') then
return original_value;
else
return new_value;
end
Where using $$NO_UPDATE$$ is a sentinel value for not updating. A potential downside of this solution is the typing of columns as a string type. You always need to use string types (I'm not sure if there are databases that would supports dynamic parameters and return types in this situation).
Let me rephrase your problem and you please tell me if this is right:
You want to be able to have the update process
sometimes you only update for a specific x
sometimes you only update for a specific y
sometimes you update for specific x and y combined
Correct? If 'yes' then the next issue is implementation possibilities.
You suggested trying to put the column itself into the parameter. Even if that's possible I'd still recommend against it. The code will get confusing.
I suggest you create a java method that builds and returns the query string (or at least the 'where' clause) based on your available parameters (x, y, etc)
Your code for invoking the JDBC Prepared statement will invoke that method to get a query String.
You will still benefit from using prepared statements. The cost is that your database will be caching several different statements instead of one, but I imagine that is a minimal issue.
You can think of auxiliar "?" variable for each column which will manage if the column should be updated or not.
update table
set x = case when 0 = ? then x else ? end,
y = case when 0 = ? then y else ? end
where etc;
Passing 0 for each 0 = ? will not update the column whereas passing 1 will update it to the value you specified.
I am working with a program that i have a record for every user. My users have a property with key, PhoneNumber , and its value is an array of strings, [454457,897356]. For example if i wanted to use cypher query:
Start n=node(1)
Return n
It returns 1 record for my node(one row) that the value of column PhoneNumber is an array.
But i want to have record numbers according to the number of values in my array, means that for my example, the query returns 2 records(2 rows) and all of its attributes be the same but in the PhoneNumber column one of them has the value 454457 and the other has the value 897356. Is any way to do that? do i change my cypher query or make some changes in my java code?
Thanks.
There is no way to do that yet, within Cypher. I've submitted a request for it, though:
https://github.com/neo4j/neo4j/issues/30
I'm trying to write a JTable that takes the data from a ResultSet and uses that to create a dynamic sized table with appropriate column names and row data values from the ResultSet but I can't get JDBC to get the column names for me dynamically.
I know my select statement is good! I can print the results out easily with my ResultPrinter class that I wrote but I can't seem to get the column names for some reason.
The code: http://pastebin.com/SSNdCkNu
The output:
Connected to DB!
SNUM, SNAME, STATUS, CITY, SUPPLIERS_ID_SEQ // printed by static Suppliers class
Columns: 5 // result set shows there are 5 valid columns as expected
Exception in thread "main" java.sql.SQLException: Invalid column index: getValidColumnIndex
at oracle.jdbc.driver.OracleResultSetMetaData.getValidColumnIndex(OracleResultSetMetaData.java:138)
at oracle.jdbc.driver.OracleResultSetMetaData.getColumnName(OracleResultSetMetaData.java:306)
at Main.main(Main.java:15)
JDBC column indexes start from 1 and not 0. As far as possible, it is better to retrieve data using column names to avoid hard dependency on the order of columns in the results.
Column index starts by 1. So increase your variable pointing column variable by 1.
How can I retrieve the last entered value of the column in the database (MS ACCESS 2007)
I used the following code
String sql = "SELECT Last(RegNumber) FROM Death ";
but it does not work in MS ACCESS and when I run the program Error generates as
java.sql.SQLException: Column not found
but I have created a column in database as RegNumber
I am using Java for programming in which I used this query
EDIT:
RegNumber is in String form not in integer form so I cant use DESC or ASC
Please help me
Sort your table by whatever criteria you'd like and use SELECT TOP 1 * FROM myTable ORDER BY RegNumber ASC.
Or ORDER BY incrementingId DESC
Basically there must be some logical order to the sorting for what you refer to as the "last entered column" (which I assume means row, not column)
EDIT: Your function is correct in Access, and should return the correct value. However Java may not interpret it correctly. Try your query in an Access native query, then try debugging your Java. If it's simply that Java does not support this function, consider using the built in ResultSet() functions in Java.sql
ResultSet rs = ....;
rs.last();
int RegNumber = rs.getRow();
I do not know about the last() function in MS ACCESS, but I have another idea:
Usually there is an automatically generated id for each table, so you can sort on it and get the first record from the result set like this:
SELECT RegNumber
FROM Death
ORDER BY id DESC
That depend of your database structure.
Typically with table come some unique identifier, if you are sure that it comes always in order to database you could use function MAX to retrieve the identifier and then whole row.
Another scenario is just to a timestamp columns that describe the time when column was created , this approach satisfying if the sequence is really crucial if not the id should be enough.
Following will return the last and lastest RegNumber :
SELECT RegNumber FROM Death ORDER BY RegNumber DESC