JavaWeb学习笔记 日期转换 番外篇 起到作用

本次是使用 PreparedStatement 进行多组类似数据的插入,使用过程中preStmt.setDate()的方法,其中,setDate的第二个参数为 java.sql.Date;的类型而不是java.util.Date;的类型。

所以在获取当前时间时,会出现问题。其中,setDate的第二个传入的参数是string类型,所以想到,使用之前的方法,把日期转换成string类型,再传入应该可以解决问题。

下面附上代码

package com.duan.testsql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Date;

import cn.itcast.jdbc.example.utils.JDBCUtils;
public class Example11 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Connection conn = null;
		PreparedStatement preStmt = null;
		try
		{
			conn =  JDBCUtils.getConnection();
			String sql = "INSERT INTO users(name,password,email,birthday)"+"VALUES(?,?,?,?)";
			preStmt = conn.prepareStatement(sql);
			
			NowDate nd = new NowDate();
			String date =nd.getNowDateToString();
			for(int i = 0; i < 5 ; i++)
			{
					preStmt.setString(1,"name"+i);
					preStmt.setString(2, "password"+i);
					preStmt.setString(3, "email"+i+"@itcast.cn");
					preStmt.setDate(4, Date.valueOf(date));
					preStmt.addBatch();
					
				
			}
			preStmt.executeBatch();
			
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally
		{
			JDBCUtils.release(null, preStmt,conn);
			
		}
	}

}


 

 

 

package com.duan.testsql;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NowDate {
	public  Date getNowDate() {  
	    Date currentTime = new Date();  
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");  
	    String dateString = formatter.format(currentTime);  
	    ParsePosition pos = new ParsePosition(0);  
	    Date currentTime_2 = formatter.parse(dateString, pos);  
	    return currentTime_2; 
	}  
	public  String getNowDateToString() {  
	    Date currentTime = new Date();  
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
	    String dateString = formatter.format(currentTime);   
	    return dateString; 
	}  
}


 

 

问题得到很好解决,可以方便的把当前时间插入到数据库中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值