I've a table with a column TIME type (named myTime
).
string t ="15:50:00";
How to convert and insert this string into myTime
column (HH:MM:SS).
Thank you!
I've a table with a column TIME type (named myTime
).
string t ="15:50:00";
How to convert and insert this string into myTime
column (HH:MM:SS).
Thank you!
You may use TIME Datatype. For example,
CREATE TABLE tests (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(500) NOT NULL,
start_time TIME,
end_time TIME
);
You can use String
data type to represent the Time
value, or you can use MySQL Time
data type and in your Java code use preparedStatement.setTime()
, for example:
Your table is:
CREATE my_table (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR2(30) NOT NULL,
time_from TIME
);
Your Java code can look like this:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MySQLDatabaseDemo {
Connection conn = null;
PreparedStatement preparedStatement = null;
public static Connection getConnection() throws Exception {
String driver = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://localhost/databaseName";
String username = "root";
String password = "root";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username,
password);
return conn;
}
/**
* @param args [0] = value of "id"
* [1] = value of "name"
* [2] = value of "time_from"
*/
public void insertRowWithTimeDatatype(String[] args) {
String query = "insert into my_table (id, name, timefrom) " +
"values (?, ?, ?)";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(args[2]);
Time time = new Time(date.getTime());
try {
conn = getConnection(); // getConnection() is YOUR method
preparedStatement = conn.prepareStatement(query);
preparedStatement.setInt(1, Integer.parseInt(args[0]));
preparedStatement.setString(2, args[1]);
preparedStatement.setTime(3, time);
// Execute statement and return the number of rows affected
int rowCount = preparedStatement.executeUpdate();
System.out.println("Number of rows affected: " + rowCount);
} finally {
preparedStatement.close();
conn.close();
}
}
}
You can use setString()
to set any SQL data type. Try something like this:
prepStatement.setString("myTime", "15:50:00");
I haven’t got the experience myself, but the best you can do is to keep your time in a LocalTime
object in Java and use yourPreparedStatement.setObject(parameterIndex, yourTime);
to set the time as a value in your SQL insert
or update
statement. I’m sure you can find code examples, tutorials, documentation, etc., out there. Please go search.
So where do you get the LocalTime
object from?
LocalTime yourTime = LocalTime.parse(t);
(where t
is your time string, for example 15:50:00
as in the question)