如何在 Java 中将时间(HH:MM:SS)插入 MySQL 数据库表中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45657196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:49:33  来源:igfitidea点击:

How to insert Time ( HH:MM:SS) into MySQL Database table in Java?

javamysqlsqltimelocaltime

提问by D?ng Hoàng

I've a table with a column TIME type (named myTime). string t ="15:50:00"; How to convert and insert this string into myTimecolumn (HH:MM:SS).

我有一个列 TIME 类型(名为myTime)的表。字符串 t="15:50:00"; 如何转换此字符串并将其插入myTime列 (HH:MM:SS)。

Thank you!

谢谢!

回答by Sai Munikumar Nerukonda

You may use TIMEDatatype. For example,

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

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

回答by Binyamin Regev

You can use Stringdata type to represent the Timevalue, or you can use MySQLTimedata type and in your Java code use preparedStatement.setTime(), for example:

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

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:

您的 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();
      }
   }
}

回答by Usagi Miyamoto

You can use setString()to set any SQL data type. Try something like this:

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

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

回答by Ole V.V.

I haven't got the experience myself, but the best you can do is to keep your time in a LocalTimeobject in Java and use yourPreparedStatement.setObject(parameterIndex, yourTime);to set the time as a value in your SQL insertor updatestatement. I'm sure you can find code examples, tutorials, documentation, etc., out there. Please go search.

我自己没有经验,但您能做的最好的事情是将时间保留LocalTime在 Java中的对象中,并用于yourPreparedStatement.setObject(parameterIndex, yourTime);将时间设置为 SQLinsertupdate语句中的值。我相信您可以在那里找到代码示例、教程、文档等。请去搜索。

So where do you get the LocalTimeobject from?

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

LocalTime yourTime = LocalTime.parse(t);

(where tis your time string, for example 15:50:00as in the question)

t您的时间字符串在哪里,例如15:50:00在问题中)