我正在尝试将数据从postgresql数据库导出到MongoDB。我已成功创建了JSON格式的字符串,当我将此json存储在mongoDB集合中时,只存储第一个条目。 这是我的代码: 公共课jsonTobson {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
try{
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://localhost:5544/ddc", "postgres", "aman");
st = con.createStatement();
String sql = "select row_to_json(judge_info) FROM dp.judge_info order by judge_idno";
ResultSet rs = st.executeQuery(sql);
StringBuilder builder = new StringBuilder();
int columnCount = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 0; i < columnCount;) {
builder.append(rs.getString(i + 1));
if (++i < columnCount) builder.append(",");
}
builder.append("\r\n");
}
String resultSetAsString = builder.toString();
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "mongoTest" );
DBCollection coll = db.getCollection("newTable");
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}
DBObject dbObject = (DBObject)JSON.parse(resultSetAsString);
coll.insert(dbObject, WriteConcern.NORMAL);
DBCursor cursorDocJSON = coll.find();
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
rs.close();
st.close();
con.close();
} catch ( Exception e)
{
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
} finally {
}
}
}
答案 0 :(得分:0)
public static void main(String[] args) {
Connection con = null;
Statement st = null;
try{
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://localhost:5544/ddc", "postgres", "aman");
st = con.createStatement();
String sql = "select row_to_json(judge_info) FROM dp.judge_info order by judge_idno";
ResultSet rs = st.executeQuery(sql);
MongoClient mongoClient=null;
try {
mongoClient = new MongoClient("localhost", 27017);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DB db = mongoClient.getDB("mongoTest");
System.out.println("Connect to database successfully");
while (rs.next()) {
DBCollection coll = db.getCollection("newTable");
System.out.println("Collection selected successfully");
BasicDBObject doc = new BasicDBObject("data", rs.getString(1));
coll.insert(doc);
}
} catch ( Exception e)
{
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
} finally {
}
}
}