Java教程

Java获取系统时间并写入数据库

本文主要是介绍Java获取系统时间并写入数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package com.java1234.util;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * 数据库工具类
 */
public class DBUtil {
	 private String dbUrl ="jdbc:mysql://localhost:3306/wuye?useSSL=false";         //数据库连接地址
	    private String dbUseName = "root";                                       //用户名
	    private String dbPassword = "111111";                                    //密码
	    private String jdbcName = "com.mysql.cj.jdbc.Driver";                       //驱动名称

    /**
     * 获取数据库连接
     * @return
     * @throws Exception
     */
    public Connection getCon()throws Exception{
        Class.forName(jdbcName);
        Connection con = DriverManager.getConnection(dbUrl,dbUseName,dbPassword);
        return con;
    }

    /**
     * 关闭数据库连接
     * @param con
     * @throws Exception
     */
    public void closeCon(Connection con)throws Exception{
        if(con!=null){
            con.close();
        }
    }

   public static void main(String[] args){
        DBUtil dbUtil = new DBUtil();
        try {
            dbUtil.getCon();
            System.out.println("数据库连接成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据库连接失败!");
        }

    }
}

连接数据库,可验证数据库是否连接成功 ,需修改自己的用户名和密码

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

import javax.swing.JOptionPane;

import com.java1234.util.DBUtil;

public class time {
	
	private Date date ;
	private DBUtil dbUtil;
	private Timestamp timestamp ;
	
	public time() {
		super();
	}
	public time(Date date,Timestamp timestamp) {
		this.date=date;
		this.timestamp=timestamp;
		
	}
	
	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public Timestamp getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Timestamp timestamp) {
		this.timestamp = timestamp;
	}

	public int add(Connection con,time t)throws Exception{
		String times;
		String sql="insert into t_time values(null,?)";
		PreparedStatement pstmt=con.prepareStatement(sql);
		pstmt.setTimestamp(1,timestamp);
		return pstmt.executeUpdate();
	}
	
	
	private void timeadd(time t) {
		dbUtil=new DBUtil();
		Connection con=null;
		try {
			con = dbUtil.getCon();
			int n = t.add(con,t);
			if(n==1) {
				JOptionPane.showMessageDialog(null,"添加成功!");
			}else {
				JOptionPane.showMessageDialog(null,"添加失败!");
			}
		}catch(Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null,"添加失败!");
		}
	}
	
	public static void main(String args[]) {
		Date date = new Date();
		Timestamp timestamp = new Timestamp(date.getTime());
		time t=new time (date,timestamp);
		t.timeadd(t);
	}
	

	


}

获取系统时间并写入数据库中

这篇关于Java获取系统时间并写入数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!