This question already has answers here:
Getting the date from a ResultSet for use with java.time classes
(3 answers)
Closed 4 years ago.
I run a simple query to retrieve a row from a MySQL database.
I get ResultSet and I need to retrieve a LocalDateTime object from it.
My DB table.
CREATE TABLE `some_entity` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(45) NOT NULL,
`text` varchar(255) DEFAULT NULL,
`created_date_time` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
I need to retrieve some entity by id.
String SELECT = "SELECT ID, TITLE, TEXT, CREATED_DATE_TIME FROM some_entity WHERE some_entity.id = ?";
PreparedStatement selectPreparedStatement = connection.prepareStatement(SELECT);
try {
selectPreparedStatement.setLong(1, id);
ResultSet resultSet = selectPreparedStatement.executeQuery();
if (resultSet.next()) {
Long foundId = resultSet.getLong(1);
String title = resultSet.getString(2);
String text = resultSet.getString(3);
LocalDateTime createdDateTime = null;// How do I retrieve it???
}
} catch (SQLException e) {
throw new RuntimeException("Failed to retrieve some entity by id.", e);
}
Try retrieving this as java.sql.Timestamp and then converting to LocalDateTime using Timestamp.toLocalDateTime:
LocalDateTime createdDateTime = resultSet.getTimestamp(4).toLocalDateTime()
EDIT: As Gord Thompson pointed out in his comment, there's an even better solution when working with a recent enough JDBC driver:
resultSet.getObject(4, LocalDateTime.class)
This skips creating a redundant java.sql.Timestamp instance.
Related
So I'm trying to add to database using JDBC with HSQLDB from files. And I need to insert the List<Object> as a variable into the database.
This is what it looks like as a Java object:
public class Plant {
private Long id;
private String plantName;
private List<PlantParts> plantParts;
...
}
public class PlantParts {
private String leaves;
private String pedicle;
private String petals;
...
}
In folder resources I have a file called insert_plant.sql that contains this query:
INSERT INTO PLANTS (id, plantname, plantparts)
VALUES (NEXT VALUE FOR sequence, ?, ?);
And the table is generated with this:
CREATE SEQUENCE sequence START WITH 1;
CREATE TABLE PLANTS (
id BIGINT NOT NULL PRIMARY KEY,
plantname VARCHAR(255) NOT NULL,
plantparts VARCHAR(255) NULL, //No idea what to put here
);
And now in Java I am calling this:
public static void insertIntoOrderTable(BasicDataSource basicDataSource, String plantname, List<PlantParts> plantparts) throws SQLException{
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = basicDataSource.getConnection();
stmt = conn.prepareStatement(Util.readFileFromClasspath("insert_plant.sql"), new String[]{"id"});
stmt.setString(1, plantname);
stmt.setString(2, plantparts); //And no idea what to do here
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
The requests will usually come as a JSON:
{ "id": 5,
"plantName": "awesome plant",
"plantParts":[
{"leaves":"green","pedicle":"yellow","petals":"many"},
{"leaves":"red","pedicle":"yellow","petals":"few"}
]
}
My guess is that they should be held in the separate tables, but how can I do that and when I would need to get the object then how could I get it as a whole.
The SQL model of your data will be different from Java in how the Plant and PlantParts objects are linked together. In the Java model, Plant has a collection of PlantParts objects. In the SQL model, the PlantParts objects reference the Plant object.
So you need these two tables:
CREATE TABLE plants (
id BIGINT NOT NULL PRIMARY KEY,
plantname VARCHAR(255) NOT NULL,
);
CREATE TABLE plantparts (
id BIGINT NOT NULL PRIMARY KEY,
leaves VARCHAR(255) NOT NULL,
pedicles VARCHAR(255) NOT NULL,
petals VARCHAR(255) NOT NULL,
plantid BIGINT NOT NULL,
FOREIGN KEY (plantid) REFERENCES plants(id)
);
Note there is no column in the plants table for the PlantParts objects. The data for the PlantParts in your JSON object goes into two rows of the plantparts table. The plantid column of both of these rows will contain the id of the Plant object, which is 5.
This question already has answers here:
How to use dynamic table name in SELECT query using JDBC
(3 answers)
Closed 6 years ago.
String sql2 = "create table ? ( id int not null auto_increment, fullname
varchar(30) not null, primary key (id) )";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
stmt2.setString(1, username);
stmt2.execute();
stmt2.close();
from above statements, i got error message('john' as table name):
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near ''john' ( id int not null
auto_increment, fullname varchar(30) not null, primary ' at line 1
eclipse says the error is in this line:
stmt2.execute();
please help guys...tq
You can't use a parameter for the table name in a CREATE TABLE statement.
Instead simply build the SQL string using the variable:
String sql2 = "create table " + username + " ( id int not null auto_increment, fullname
varchar(30) not null, primary key (id) )";
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(sql2);
I have a method which insert a record to mysql database as bellow,
public boolean addOrganization(OrganizationDTO organizationDTO) {
Connection con = null;
try {
String insertOrganizationSQL = "INSERT INTO organizations (org_id, org_name) VALUES(?, ?)";
con = JDBCConnectionPool.getInstance().checkOut();
PreparedStatement insertOrgPS = (PreparedStatement) con.prepareStatement(insertOrganizationSQL);
insertOrgPS.setString(1, organizationDTO.getOrg_id());
insertOrgPS.execute();
return true;
} catch (Exception e) {
JDBCConnectionPool.getInstance().checkIn(con);
logger.error(e.getLocalizedMessage());
e.printStackTrace();
return false;
} finally {
JDBCConnectionPool.getInstance().checkIn(con);
}
}
database table,
CREATE TABLE `organizations` (
`org_id` varchar(5) NOT NULL,
`org_name` varchar(100) DEFAULT NULL,
`sys_dat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`user` varchar(100) NOT NULL,
PRIMARY KEY (`org_id`)
)
what I need is, when I insert a new record if, that is a duplicate exit the method without trying to insert and inform the user that it is a duplicate record. Is it possible to do without writing another method to search the record before inserting?
I would add a UNIQUE constraint to your table. For example, if org_name needs to be unique:
ALTER TABLE organizations ADD UNIQUE (org_name);
Then observe what's returned when you try to insert a duplicate record through Java. Add code to check for this, and if it occurs, display the message to your user.
Here is the reference documentation for ALTER TABLE.
Thats right, Alter table will surely help.
In your case, let say, both org_id and org_name is there, I would add unique in both, just avoid any confusion later.
I'm having trouble with retrieving queries from my SQL database. I can get the blasted things added to the database, but I'm having an inordinate amount of difficulties performing the reverse. Three things, in order:
The SQL Table itself:
CREATE TABLE patientInstructions (
id INT UNSIGNED AUTO_INCREMENT,
lastUpdated datetime NOT NULL,
PatientID BIGINT UNSIGNED NOT NULL,
HCPID BIGINT UNSIGNED NOT NULL,
OVid BIGINT UNSIGNED NOT NULL,
urlLink VARCHAR(250) NOT NULL,
linkInstructions VARCHAR(500) NOT NULL,
linkName VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
) AUTO_INCREMENT=1 ENGINE=MyISAM;
The method call that is failing (I'm getting -1L instead of the actual data value stored in the database, which is why I know there's a problem in the first place):
public String getLastUpdated(long ovID) throws DBException {
try {
return psiDAO.getLastUpdated(ovID);
} catch (myOwnException e) {
e.printStackTrace();
return "-1L";
}
}
And finally, the method call which is failing:
public String getLastUpdated(long ovId) throws DBException {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = factory.getConnection();
ps = conn.prepareStatement("SELECT * FROM patientInstructions"
+ " WHERE ovId=?");
ps.setLong(1, ovId);
ResultSet rs = ps.executeQuery();
java.util.Date updated = new java.util.Date();
updated = rs.getTime("lastUpdated");
return updated.toString();
} catch (SQLException e) {
e.printStackTrace();
throw new DBException(e);
} finally {
DBUtil.closeConnection(conn, ps);
}
}
What Java object matches a SQL Datetime? I've tried rs.getTimestamp, rs.getDate, etc. but haven't had any more success (though I'm not ruling out that I botched those up either). Am I making a mistake transferring the data from the resultset back to Java object?
You must call ResultSet.next() on a ResultSet before accessing each row, including the first. You're not doing that here; the exception message should actually be telling you this.
There are three classes: java.sql.Date, java.sql.Time, and java.sql.Timestamp. I'm not sure which one most closely corresponds to a DATETIME in SQL. All three derive from java.util.Date, which is why you are able to assign the result of calling rs.getTime to one.
I don't have a setup here that would allow me to test it, but I would try using one of the types from java.sql.* and see what results that gives you.
Whoops! I posted my answer before Ernest's and I didn't even notice the missing rs.next(). That is definitely your problem, and I bet java.util.Date will work just fine for you, with that change.
Since your datatype is datetime, you will need to use getTimestamp()... see here for more datatype mapping information.
So, your code should look something like this:-
...
ResultSet rs = ps.executeQuery();
String updated = "";
if (rs.next()) {
updated = rs.getTimestamp("lastUpdated").toString();
}
rs.close();
ps.close();
return updated;
Please paste the exception here. You need to call ResultSet's next method before retrieving the values from the result set. Also, try java.sql.Timestamp lastUpdatedTimestamp = getTimestamp("lastUpdated")
If needed , you can convert timestamp to String later.
Table
id int(11) No auto_increment Change Drop Primary Index Unique Fulltext
email varchar(45) latin1_swedish_ci No Change Drop Primary Index Unique Fulltext
billpayment tinyint(1) No Change Drop Primary Index Unique Fulltext
dispatch tinyint(1) No Change Drop Primary Index Unique Fulltext
address varchar(75) latin1_swedish_ci Yes NULL Change Drop Primary Index Unique Fulltext
phone int(11) Yes NULL Change Drop Primary Index Unique Fulltext
created_at datetime No Change Drop Primary Index Unique Fulltext
totalbillamount float Yes NULL Change Drop Primary Index Unique Fulltext
Java Code:
sql = "insert into session_shopping (email,billpayment,dispatch,address,phone,created_at,totalbillamount) values(?,?,?,?,?,?,?)";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, email);
ps.setBoolean(2, false);
ps.setBoolean(3, false);
ps.setString(4, "");
ps.setInt(5, 0);
java.util.Date date = new java.util.Date();
long t = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(t);
ps.setDate(6, sqlDate);
ps.setFloat(7, 00.0f);
int newId = ps.executeUpdate();
System.out.println("newId" + newId);
if (newId == 1) {
sql = "select * from session_shopping where id = ?";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setInt(1, newId);
ResultSet reS = ps.executeQuery();
Session s = new Session();
s.setId(reS.getInt("id"));
s.setEmail(reS.getString("email"));
System.out.println("retreived");
return s;
} else {
System.out.println("unable to save");
}
This code fails because int newId is boolean
What i want to do is. I want to retrieve the row which i added just now.
executeUpdate will return the number of rows affected, not the current row .
Try this
ResultSet rs = aStatement.executeQuery("SELECT LAST_INSERT_ID()");
while(rs.next())
{
key = rs.getInt(1);
}
The value returned by executeUpdate has nothing to do with your ID.
Before we go to getting your ID, you can start off by setting email in the Session from your email variable rather than pulling it back out of the database.
As things stand, the only way I can think of to get the newly inserted ID is by changing your SQL thus:
sql = "select max(id) from session_shopping";
This will give you problems if you get another insert before you pick out the maximum ID though. To prevent that, put the select in the same transaction as your insert.