Java中向数据库插入时间

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

你可能感兴趣的:(java)