`
Java-feifeiok
  • 浏览: 22827 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
文章分类
社区版块
存档分类
最新评论

Java 往数据库插入时间格式的数据

阅读更多

package org.interview.hlf;

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;
/**
 * 时间插入数据库的两种方式:
 * 1  用java.sql.Date:将java.util.Date(),调用该类的getTime()方法,返回一个long类型的数据,作为sql.Date()的参数就可以插入
 * 2  用格式化参数:SimpleDateFormat 的df.format()将时间转换成字符串插入进入
 */
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();
        }
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics