最近因工作需要,需要做数据同步。java通过jdbc读取表中的数据虽然不复杂,但是在处理时间timestamp类型时获取的是对象,暂时未处理,先将直接读取表中的数据读取出来
//用于连接数据库(oracle 其他数据库改一下驱动即可)
public static Connection getOracleConn(String urlName, String userName, String passwordName) {
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
String url = PropertiesUtil.getValue(urlName);
String username = PropertiesUtil.getValue(userName);
String password = PropertiesUtil.getValue(passwordName);
conn = DriverManager.getConnection(url, username, password);// 获取连接
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 根据sql查询结果
* @param conn
* @param sql sql
* @return
*/
public static List<Map<String, Object>> getResultMap(Connection conn, String sql) {
List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
Map<String, Object> resultMap;
try {
Statement ps = conn.createStatement();
ResultSet rs = ps.executeQuery(sql);
while(rs.next()) {
ResultSetMetaData metaData = rs.getMetaData();
resultMap = new HashMap<String, Object>();
for(int i=1;i<=metaData.getColumnCount();i++) {
resultMap.put(metaData.getColumnName(i), rs.getObject(i));
}
listMap.add(resultMap);
}
} catch (SQLException e) {
e.printStackTrace();
}
return listMap;
}
/**
* 插入单条数据
* @param conn
* @param sql
* @return
*/
public static boolean insert(Connection conn, String sql) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
return ps.executeUpdate() > 0 ? true : false;
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
public static void main(String[] args) {
String id = UUID.randomUUID().toString();
String sql = "insert into t_user(id, username, password, sex, job, age, addr, company, mail, tel, birth) "
+ "values('" + id + "','test', 'test', '男', 'IT', 22, 'wuhan', 'custom', 'test.com', '1234', to_date('2012-12-01 13:23:22', 'yyyy-MM-dd HH24:mi:ss'))";
System.out.println(sql);
Connection oracleConn = getOracleConn("url", "username", "password");
insert(oracleConn, sql);
try {
oracleConn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
此代码在查询的时候,对于时间戳timestatmp类型的数据读取时是对象类型的,暂时不知道怎么处理。