2017-08-13 128 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如問題)

相關問題