共計(jì) 1665 個(gè)字符,預(yù)計(jì)需要花費(fèi) 5 分鐘才能閱讀完成。
要將指定時(shí)間添加到數(shù)據(jù)庫,你需要使用 JDBC(Java 數(shù)據(jù)庫連接)來連接到數(shù)據(jù)庫并執(zhí)行相應(yīng)操作。
以下是一個(gè)示例代碼,演示如何將指定時(shí)間添加到數(shù)據(jù)庫中:
import java.sql.*;
public class InsertTimeToDatabase {????public?static?void?main(String[]?args)?{
????????//?數(shù)據(jù)庫連接信息
????????String?url?=“jdbc:mysql://localhost:3306/mydatabase”;
????????String?username?=“root”;
????????String?password?=“password”;
????????Connection?conn?=?null;
????????PreparedStatement?pstmt?=?null;
????????try?{
????????????//?連接數(shù)據(jù)庫
????????????conn?=?DriverManager.getConnection(url,?username,?password);
????????????//?SQL 插入語句
????????????String?sql?=“INSERT?INTO?mytable?(time_column)?VALUES?(?)”;
????????????//?創(chuàng)建 PreparedStatement 對(duì)象
????????????pstmt?=?conn.prepareStatement(sql);
????????????//?指定時(shí)間
????????????java.util.Date?date?=?new?java.util.Date();
????????????java.sql.Timestamp?timestamp?=?new?java.sql.Timestamp(date.getTime());
????????????//?設(shè)置參數(shù)
????????????pstmt.setTimestamp(1,?timestamp);
????????????//?執(zhí)行插入操作
????????????int?rows?=?pstmt.executeUpdate();
????????????if?(rows?>?0)?{
????????????????System.out.println(“時(shí)間已成功插入到數(shù)據(jù)庫中!”);
????????????}
????????}?catch?(SQLException?e)?{
????????????e.printStackTrace();
????????}?finally?{
????????????//?關(guān)閉連接和釋放資源
????????????try?{
????????????????if?(pstmt?!=?null)?{
????????????????????pstmt.close();
????????????????}
????????????????if?(conn?!=?null)?{
????????????????????conn.close();
????????????????}
????????????}?catch?(SQLException?e)?{
????????????????e.printStackTrace();
????????????}
????????}
????}
}
你需要將示例代碼中的 url
、username
和password
修改為你自己數(shù)據(jù)庫的連接信息,并根據(jù)你的表結(jié)構(gòu)修改 SQL 插入語句中的表名和列名。
然后,使用 setTimestamp
方法將指定時(shí)間設(shè)置為參數(shù),并執(zhí)行插入操作。如果插入成功,將輸出 " 時(shí)間已成功插入到數(shù)據(jù)庫中!"。
請(qǐng)注意,這只是示例代碼,實(shí)際應(yīng)用中你可能需要處理異常、關(guān)閉連接和釋放資源等。另外,確保你已經(jīng)導(dǎo)入了正確的 JDBC 驅(qū)動(dòng)程序。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!