2017-08-13 25 views
-1

我有一个列TIME类型的表(名为myTime)。 string t =“15:50:00”; 如何将该字符串转换并插入myTime列(HH:MM:SS)。如何在Java中的MySQL数据库表中插入时间(HH:MM:SS)?

谢谢!

+0

你甚至可以用“VARCHAR”作为MySQL表的数据类型,并直接存储为字符串。稍后,您可以获取字符串并根据需要通过Java代码 –

+2

将其转换为Date对象!我需要TIME类型不是DATETIME –

+0

欢迎来到堆栈溢出。请在发布之前研究您的问题。在很多情况下,您会通过搜索引擎更快地找到答案。如果你不这样做,当你告诉我们你找到了什么,你没有找到什么,你尝试过什么以及你还缺少什么时,我们可以更准确地指导你。 –

回答

0

您可以使用String数据类型来表示Time值,也可以使用MySQL的Time数据类型和在Java代码中使用preparedStatement.setTime(),例如:

你的表是:

CREATE my_table (
    id   INT   PRIMARY KEY AUTO_INCREMENT, 
    name  VARCHAR2(30) NOT NULL, 
    time_from TIME 
); 

Java代码可以是这样的:

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(); 
     } 
    } 
} 
+0

请不要教导年轻人使用过时的和臭名昭着的麻烦课程Date,Time和SimpleDateFormat。至少不是第一种选择,也没有任何保留。今天我们好多了。 –

1

您可以使用TIME数据类型。 例如,

CREATE TABLE tests (
    id INT PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(500) NOT NULL, 
    start_time TIME, 
    end_time TIME 
); 
+0

我有一个列(名为myTime)TIME类型的表。但我不能在此列中插入字符串t =字符串t =“15:50:00”。如何转换并将此字符串插入myTime列。请! –

+0

请使用'setString()'为SQL数据类型。 –

0

您可以使用setString()设置任何SQL数据类型。尝试是这样的:

prepStatement.setString("myTime", "15:50:00"); 
0

我没有经验自己,但你能做的最好的是保持你的时间在Java中的LocalTime对象,并使用yourPreparedStatement.setObject(parameterIndex, yourTime);设置时间为一个值你SQL insertupdate声明。我相信你可以在那里找到代码示例,教程,文档等。请去搜索。

那么你从哪里得到LocalTime对象呢?

LocalTime yourTime = LocalTime.parse(t); 

(其中t是你的时间字符串,例如15:50:00如问题)

相关问题