java讀取mongoDB某個資料庫的集合的指定欄位值,並存入mysql資料庫指定表中
阿新 • • 發佈:2019-02-05
1、查詢mongodb單個欄位的所有值內容:db.getCollection('amac').find({},{"managerName":1,"_id":0}) //PS:"_id":0表示不顯示id值
java:
//mongoDB資料讀取,存入MYSQL資料庫 private static void readMongo(){ Connection conn = MysqlUtil.getConnection();//連線mysql Statement statement = null; MongoClient mongoClient=new MongoClient("119.xx.xx.xxx",27017);//連線mongoDB資料庫 DB database=mongoClient.getDB("row");//獲取資料庫 DBCollection collection = database.getCollection("amac");//集合名 DBCursor cursor = collection.find(); System.out.println("從資料集中讀取資料:"); while(cursor.hasNext()){ BasicDBObject bdbObj = (BasicDBObject) cursor.next(); if(bdbObj != null){ String managerName=bdbObj.getString("managerName");//讀取mongoDB資料庫row的amac集合的指定欄位managerName try{ statement =conn.createStatement(); String sql="insert into manager(managerName) values('"+managerName+"')";//存入mysql資料庫的機構列表 statement.execute(sql); } catch(SQLException e) { e.printStackTrace(); }finally { if(null!=statement) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } System.out.println("over."); }
其中getConnection()函式如下
//連線資料庫
private static Connection connection=null; private static String username="user"; private static String password="password"; private static String DB_URL="jdbc:mysql://localhost:3306/mingzi?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8"; private static String DB_DRIVER="com.mysql.jdbc.Driver";public static Connection getConnection() { try { Class.forName(DB_DRIVER); connection=DriverManager.getConnection(DB_URL, username, password); System.out.println("連線資料庫成功:"+connection); } catch (Exception e) { System.out.println("資料庫連線異常..."); e.printStackTrace(); } return connection;}