Java中向数据库插入时间

本文介绍了使用Java将当前时间插入数据库的两种方法:一是通过java.sql.Date类转换为SQL兼容的时间格式;二是利用SimpleDateFormat将Date对象转换为字符串再进行插入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java.util.Date时间插入数据库的两种方式:
1、用java.sql.Date:将java.util.Date(),调用该类的getTime()方法,返回一个long类型的数据,作为sql.Date()的参数就可以插入

2、用格式化参数:SimpleDateFormat 的df.format()将时间转换成字符串插入进入

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDate {

    public static void main(String[] args) {
        
        testDate1();
        testDate2();
    }
    
    static void testDate1(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test");
            Statement stmt = conn.createStatement();
            Date birthday1 = new Date();
            java.sql.Date birthday = new java.sql.Date(birthday1.getTime());
            String sql = "insert into testdate(name,birthday) values('fff'"+",'"+birthday+"')";
            System.out.println(sql);
            stmt.execute(sql);
        } catch (ClassNotFoundException e) {
            System.out.println("找不到类文件");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    static void testDate2(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test");
            Statement stmt = conn.createStatement();
            Date birthday1 = new Date();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String birthday = df.format(birthday1);
            String sql = "insert into testdate(name,birthday) values('fff'"+",'"+birthday+"')";
            System.out.println(sql);
            stmt.execute(sql);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("找不到类文件");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

 

转载自:http://hi.baidu.com/perxiaozi/item/ad7e1c1058bfa18488a956c1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值