Selecting a record from a mysql db - java

I am trying to select data from my db, but instead of getting a certain field I get "".
My table name is locations and it's look like this:
id - int,
location - varchar and time - timestamp.
I would like to select the last location based on the time, here is my code:
this.select = this.conn.createStatement();
ResultSet result = select.executeQuery("SELECT location FROM locations ORDER BY time DESC Limit 1");
result.next();
System.out.println(result.getString(1));
I remind you the output is "";

To identify the column in your resultSet you can use:
result.getString("location");

did u try ?
System.out.println(result.getString(0));

Related

update statement with dynamically changing rows using prepared statement

I am planning to execute an update statement using a prepared statement that makes use of a dynamically changing number of columns. for eg: in the first update statement I update only name and age of a table. in the second instance, I update age, city, state, country..etc. in the next instance, I update 150 columns like this.
can someone provide me what is the perfect approach for this in java?
following is the example
If the user provides input for name and age then I update
UPDATE table1 set name = <> ,age = <>;
If the user provides input for city name state country and pin then the update statement should be like this-
UPDATE table1 set name = <>, city = <>,state= <>,country=<>, pin = <>;
Build your sql query like this
update demotable set col1 = case when #col1 is null then col1 else #col1 end
OR
Here #col is passed as value from front end.
from which you may create dynamic sql
declare #col1 nvarchar(max) /// from front you can pass your column value with its column name like: col1 = 'col1'
declare #Query = 'update demotable set = ' + #col1 /// it create query as update demotable set col1 = 'col1'
PREPARE stmt1 FROM #Query ;
EXECUTE stmt1
DEALLOCATE PREPARE stmt1;
I am new to MYSQL but this logic will surely work.
You can write one statement like this:
UPDATE table1
SET name = COALESCE(?, name),
age = COALESCE(?, age),
city = COALESCE(?, city),
. . .
Notes:
This assumes that the values are not being set to NULL.
The ? is a placeholder for a parameter. Don't munge query strings with user input.
Presumably you want a WHERE clause to limit what rows get updated.

Java ResultSet get nothing but sql get result in mysql

I am using MySql database which has one table 'tradeinfo'.
Table structure:
Date TradeCode
2017.01.01 0001
2017.02.05 0002
2017.03.05 0001
My sql to find lastest trading day of the one tradecode is
SELECT TradeCode, MAX(date) most_recent_time FROM tradeinfo WHERE TradeCode = '0001'
I test the sql in Mysql db and can get right result which is "2017.03.05 0001"
But for my java code which is "lastestdbrecordsdate = rs.getDate("MOST_RECENT_TIME"); ", It ever return right result. But few days later, when run it again, I always get NULL.
My java code is:
Connection con = DriverManager.getConnection("jdbc:mysql://...",user,password);
String sqlstatement = "SELECT TradeCode, MAX(date) most_recent_time FROM tradeinfo WHERE TradeCode = '0001' ";
PreparedStatement sqlstat = con.prepareStatement(sqlstatement);
ResultSet rsquery = sqlstat.executeQuery(sqlstatement);
CachedRowSetImpl cachedRS = new CachedRowSetImpl();
cachedRS.populate(rsquery);
while(cachedRS.next() ) {
System.out.println(cachedRS.getMetaData().getColumnCount());
Date lastestdbrecordsdate = cachedRS.getDate("MOST_RECENT_TIME");
}
Is the problem that I config the mysql wrongly or I write wrong java code?
Thanks all!
You have several problems here. First, you should be using the following query:
SELECT MAX(date) most_recent_time FROM tradeinfo WHERE TradeCode = '0001'
Adding TradeCode to the select list doesn't make any sense because it is not an aggregate, but rather each record has a value for this column.
With regard to why you are getting null results, you need to call ResultSet#next() to advance the cursor to the first line:
Connection con = DriverManager.getConnection("jdbc:mysql://...", user, password);
Statement sqlstat = con.prepareStatement(sqlstatement);
ResultSet rsquery = sqlstat.executeQuery(); // DON'T pass anything to executeQuery()
if (rsquery.next()) {
Date lastestdbrecordsdate = rs.getDate("most_recent_time");
}
Another problem I just noticed is that you were passing in the query string to your call to Statement#executeQuery(). This is wrong, and you should not be passing anything to this method.

select JDBC query not retrieving records in order

I am trying to fetch records from oracle db. I have a select query which has an order by clause implemented. Now when I fire the query on the toad i get the results in correct order. i.e the order of the records at 10:00 AM is like
Record 1, Record 2,Record 3 and at 10:05 its Record 1, Record 2, Record 3. This is what i need.
Now when iam fetching it through java code, JDBC . I try to iterate the resultset, but here at 10:05 am I am getting the order like Record 2, Record 1, Record 3. Due to this when i am adding the records to the arraylist the order is not mantained.
I dont want to sort the records of arraylist after adding.
Can someone please let me know why using jdbc the records are not fetched in the order we can see using toad ?
Sample code
try{
List<TestObjVO> testResults = new ArrayList<TestObjVO>();
double statusValue = 0;
//Connection code
pstmt = conn.prepareStatement(QUERY);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
testObj = new TestObjVO();
String date = rs.getString(1);
String status = rs.getString(2);
String svc_nm= rs.getString(3);
if("SUCCESS".equalsIgnoreCase(status)){
statusValue = 1;
}else if("ERROR".equalsIgnoreCase(status)){
statusValue = -1;
}
testObj.setTime(date);
testObj.setStatus(statusValue);
testObj.setSvc_nm(svc_nm);
testResults.add(testObj);
}
SELECT query
SELECT to_char(PROBING_DATE,'DD-MM-YYYY HH24:MI:SS') AS PROBING_DATE, STATUS, SERVICE_NAME FROM TABLE_NAME WHERE PROBING_DATE >= (sysdate-30/1440) ORDER BY PROBING_DATE,SERVICE_NAME
Table
create table TABLE_NAME(
probing_date TIMESTAMP(6) not null,
status VARCHAR2(8) not null,
service_name VARCHAR2(128) not null
)
Change your select to something like this:
SELECT to_char(PROBING_DATE,'DD-MM-YYYY HH24:MI:SS') AS PROBING_DATE_STR,
PROBING_DATE,
STATUS,
SERVICE_NAME
FROM TABLE_NAME
WHERE PROBING_DATE >= (sysdate-30/1440)
ORDER BY PROBING_DATE,SERVICE_NAME;
Note there's an extra field returned and is the raw TIMESTAMP field.

PostgreSQL: Update my user table via Java

In PostgreSQL user is a reserved keyword that is used in an internal table, however I also have a separate user table in my own database that I need to use. Whenever I try to execute INSERT or UPDATE statements on the table, it generates the following error: The column name 'id' was not found in this ResultSet.
This is the Java code I am currently using:
PreparedStatement stat1 = conn.prepareStatement("SELECT id FROM user;");
PreparedStatement stat2 = conn.prepareStatement("UPDATE user SET date_created = ? , last_updated = ? , uuid = ? WHERE id = ?;");
ResultSet rs = stat1.executeQuery();
while(rs.next()){
UUID uuid = UUID.randomUUID();
String tempId = uuid.toString();
stat2.setTimestamp(1, curDate);
stat2.setTimestamp(2, curDate);
stat2.setString(3, tempId);
stat2.setLong(4,rs.getLong("id"));
stat2.executeUpdate();
}
So my question is, how could I insert or update the values in my personal user table without interfering with the keyword restriction?
Use this:
prepareStatement("UPDATE \"user\" set date_created = ?")
Or, better yet, rename your user table to something else, like users:
ALTER TABLE "user" RENAME TO users;
Escape the table name like this
select * from "user";

I'm getting an error in java and mysql connectivity..its related to date comparing in java and mysql

String x=jTextField1.getText();
After connecting to the database the query is:
String query="INSERT INTO student(A) VALUES('"+a+"') where date=' " +x+ " ';";
stmt.executeUpdate(query);
*a is a string which has a letter P assigned to it.
The error i am getting is "....check your mysql syntax....corresponding to the date='"+x'"; "
I want to compare the date entered in the textfield to the date in the mysql 'date' column and if it is correct,the 'a' value (which is P) should be written in column A in the same row of the date entered...
Please help...
Thank you...
I see a space after/before the single quote.
Furthermore date is also an SQL keyword, so better not use that as field name. You could write
`date`
Addition
Sorry, I realized that I erred (date cannot be a field queried as we are inserting a new record).
Either you mean:
String query = "INSERT INTO student(A) VALUES('P') WHERE CURRENT_DATE() = '2012-05-09'";
Or date is a field, and you just want to set another field:
String query = "UPDATE student SET A = 'P' WHERE `date` = '2012-05-09'";
Inserting new records into same table
This is not allowed to do immediately, so one has to use a temporary table.
CREATE TEMPORARY TABLE tmp (A VARCHAR(1));
INSERT INTO tmp (A)
SELECT 'P' FROM student WHERE dt = '...';
INSERT INTO student(A)
SELECT A FROM tmp;
DROP TABLE tmp;

Categories

Resources