Convert Java Timestamp to MySQL timestamp vice versa - java

How can I Convert Java Timestamp (Timestamp data type) to MySQL timestamp vice versa?

If you're using the JDBC API to access the database, and you're using a PreparedStatement to for example execute an SQL INSERT statement, then you just set the timestamp as a parameter to the PreparedStatement:
Timestamp ts = ...; // wherever you get this from
PreparedStatement ps = connection.prepareStatement("INSERT INTO MYTABLE (ts) VALUES (?)");
ps.setTimestamp(1, ts);
ps.executeUpdate();
Likewise, when you're doing a query that returns a timestamp, get it from the ResultSet by calling getTimestamp on it. Example:
Timestamp result = null;
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT ts FROM MYTABLE WHERE ...");
if (rs.next()) {
result = rs.getTimestamp(1);
}
See the JDBC Tutorial.

Without more specifics on the trouble you are having, this will be a hard question to answer. However, Java makes this relatively straightforward if you are using prepared statements. Your code would look something like this:
Connection conn = getConnection();
PreparedStatement pStmt = conn.prepareStatement("UPDATE my_table SET my_column = ? WHERE id = ?");
pStmt.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
pStmt.setInt(2, 42);
pStmt.executeUpdate();

As far as I can see from MySQL docs, java.sql.Timestamp should just work if you read it from or write it to a TIMESTAMP field in the database. So you should not need to do any conversion.

Related

SQL Query using where clause in Prepared Statement [duplicate]

This question already has answers here:
How to add a where clause in a MySQL Insert statement?
(8 answers)
Closed 5 years ago.
I am working on a gate entry system, in which i am inserting in-time and out-time. While writing sql query for out-time, it is showing error at WHERE clause. I am not able to solve the error. What will be exact SQL query?
java.util.Date date = new java.util.Date();
java.sql.Timestamp sqlTime = new java.sql.Timestamp(date.getTime());
PreparedStatement ps = con.prepareStatement("insert into ENTRY(OUTTIME) values(?,?,?,?) WHERE (ENTRY.ROLLNUMBER='"+rollno+"' AND ENTRY.OUTTIME ='NULL')");
ps.setTimestamp(4,sqlTime);
ps.executeUpdate();
You need to UPDATE the existing row
PreparedStatement ps = con.prepareStatement("UPDATE ENTRY SET OUTTIME =? WHERE ROLLNUMBER=?");
ps.setTimestamp(1,sqlTime);
ps.setString(2, rollno);
This isn't how an insert statement works. If you want to update an existing record, you'd need an update statement:
PreparedStatement ps =
con.prepareStatement("UPDATE entry SET outtime = ? WHERE rollbumber = ?");
ps.setTimestamp(1, sqlTime);
ps.setInt(2, myRollNo);
It makes no sense for an insert statement to have a WHERE clause which refers back to the same record. I propose the following code:
java.sql.Timestamp sqlTime = new java.sql.Timestamp(date.getTime());
String sql = "INSERT INTO ENTRY(OUTTIME) VALUES (?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setTimestamp(1, sqlTime);
ps.executeUpdate();
Either you update or change your insert statement as below:
"insert into ENTRY(OUTTIME) select col1 from ENTRY WHERE ENTRY.ROLLNUMBER='"+rollno+"' AND ENTRY.OUTTIME ='NULL'"
Use this code
java.util.Date date = new java.util.Date();
java.sql.Timestamp sqlTime = new java.sql.Timestamp(date.getTime());
PreparedStatement ps = con.prepareStatement("update ENTRY set OUTTIME= ? WHERE ENTRY.ROLLNUMBER='"+rollno+"' AND ENTRY.OUTTIME is NULL");
ps.setTimestamp(4,sqlTime);
ps.executeUpdate();

Calling a MSSQL stored procedure in Java

I have access to a stored procedure on a sql server which has one parameter and I can easily run it on the sql client as follow:
exec sp_name "2016/11/01"
Now I want to do the same thing in java.
PreparedStatement ps = conn.prepareStatement("sp_name ?");
ps.setString(1, "2016/11/01");
ResultSet rs = ps.executeQuery();
In rs I can see the columns' names, but zero row is returned. I think it is because of the stored procedure's parameter. Am I missing something here?
Here is the code that worked eventually:
String date= "2016/11/01"
String queryString "exec sp_dmp_pub_status ?";
PreparedStatement ps = conn.prepareStatement(queryString);
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date parsed = format.parse(date);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
ps.setDate(1, sqlDate);
ResultSet rs = ps.executeQuery();

How to get current row inserted

I have a table, and in it I have
UsernameID,UniqueID, component, coorX, coorY, coorX2, coorY2.
The UniqueID is created by Auto Increment. I want to get the current row after I insert into my table. How do I insert the current row in MySQL? I'm using Java.
In php they used
mysql_insert_id()
Can you give me an example of a script to insert the current row in MySQL using Java?
It's JDBC standard feature, see Statement.executeUpdate(String sql, int autoGeneratedKeys), example:
Statement stmt = conn.createStatement();
stmt.executeUpdate("insert into t1 (UsernameID) values (1)", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
long id = rs.getLong(1);
You can also use PreparedStatement for the same.
String ColumnsArray[] = {"columnName"};
String sqlQuery = " " // write your insert query here
PreparedStatement pstmt = conn.prepareStatement(sql,ColumnsArray);
pstmt.setString(1, "anyvalue");
pstmt.execute();
ResultSet rs = pstmt.getGeneratedKeys();
if(rs.next())
long key = rs.getLong(1);

Single quote missing in query

i am passing date in sql query using java.Below is my code that retrieve no result.
java.sql.Date d1=java.sql.Date.valueOf(startDate);
java.sql.Date d2=java.sql.Date.valueOf(enddate);
String url= "jdbc:jtds:sqlserver://"+serverName+"/"+database;;
String driver = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
System.out.println("Connected to the database!!! Getting table list...");
Statement sta = conn.createStatement();
String Sql = "Select INDEX from Table where DATE between "+d1+" and "+d2;
System.out.println("sql="+Sql);
rs = sta.executeQuery(Sql);
}
} catch (Exception e) {
e.printStackTrace();}
Query returns no row because date should be passed as '2015-02-28' but query treats date as 2015-02-28 without single quote.Please suggest.
Creating SQL statements by concatenating strings together makes your software vulnerable to SQL injection (if the values of the variables come from user input).
You should use PreparedStatement instead:
PreparedStatement sta =
conn.prepareStatement("Select INDEX from Table where DATE between ? and ?");
sta.setDate(1, d1);
sta.setDate(2, d2);
rs = sta.executeQuery(Sql);
Add single quotes
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
but the best option would be using PreparedStatement.
Try it like so:
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2 + "'";
That being said, you should look into PreparedStatements.
You have multiple issues in the query
INDEX is a reserved word and you need to escape it using backticks http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Date should be used within quotes
So the query should be
String Sql = "Select `INDEX` from Table where DATE between '"+d1+"' and '"+d2+"'";
Replace Your Query with
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
I suggest you to use PreparedStatement Instead
String query="Select INDEX from Table where DATE between ? and ?";
PreparedStatement ps=con.prepareStatement(query);
ps.setDate(1,d1);
ps.setDate(2,d2);
ps.executeQuery();

How to get query plan information from Postgres into JDBC

I want to capture the cost numbers from the query plan you get when you 'Explain' a query. Is there any way to get at this data inside of a Java ResultSet(or similar object)?
Sure, just run it as a regular statement:
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("explain analyze select * from foo");
while (rs.next())
{
System.out.println(rs.getString(1));
}
In addition to the answer supplied above, I would suggest that you make use of the ability to format EXPLAIN plans as XML in PostgreSQL 9.0 and later.
EXPLAIN ( analyze on, format xml ) SELECT ...
This will give you explain output you can more easily work with in Java by manipulating it as XML.
An other example with PreparedStatement, this time.
Like this:
PreparedStatement preparedStatement = connection.prepareStatement("EXPLAIN (ANALYZE true , VERBOSE true , BUFFERS true)" +
"SELECT * FROM Table");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
Or with a bind parameter:
PreparedStatement preparedStatement = connection.prepareStatement("EXPLAIN (ANALYZE true , VERBOSE true , BUFFERS true)" +
"SELECT * FROM Player WHERE id = ?");
preparedStatement.setLong(1, 1);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}

Categories