标签:void query nts 时间戳 driver 分享 into 2-2 cti
数据表结构:
1、实例:生成时间戳数据
package com.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Test { public static void main(String[] args) { Connection conn; Statement stmt; ResultSet rs; String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test;"; String sql = "insert into student(id,name,date) values ("; try { conn = DriverManager.getConnection(url, "sa", "Rfid123456"); stmt = conn.createStatement(); int id = 0; String name = "wang"; Long date = System.currentTimeMillis(); for(int i = 0 ; i<100; i++){ id ++; date += 100000; StringBuffer sb = new StringBuffer(sql); sb.append(id).append(", ‘").append(name).append("‘ ,").append(date).append(")"); System.out.println(sb.toString()); stmt.executeUpdate(sb.toString()); } if (stmt != null) { stmt.close(); stmt = null; } if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } } }
生成后数据如下:
2、将时间戳转为date日期格式:
select CONVERT(char(10),DATEADD(second,1507893918807/1000,‘19700101 08:00‘),120) from [test].[dbo].[student]
转换后如下:
3、实例:取Date的年月日
package com.test; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Calendar; public class Test { public static void main(String[] args) { Connection conn; Statement stmt; ResultSet rs; String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test;"; String sql = "select CONVERT(char(10),DATEADD(second,1507893918807/1000,‘19700101 08:00‘),120) AS date from [test].[dbo].[student]"; try { conn = DriverManager.getConnection(url, "sa", "Rfid123456"); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while(rs.next()){ Date date = rs.getDate("date"); //日期用Calendar比较好 Calendar cal = Calendar.getInstance(); cal.setTime(date); int year = cal.get(Calendar.YEAR); System.out.println(year); int month = cal.get(Calendar.MONTH); System.out.println(month + 1);//月份从0开始,所以 +1 } if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } } }
标签:void query nts 时间戳 driver 分享 into 2-2 cti
原文地址:http://www.cnblogs.com/Donnnnnn/p/7662261.html