SQL Server数据表数据转存至mongoDB中

 一、首先连接到sqlserver数据库,将需要转存的数据表中的列查询出来,存入到中

 二、连接到mongoDB

 三、将list中的数据循环取出,写入到mongoDB的集合中

List<StudentInfo> stuList = new List<StudentInfo>();
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=.;database=DBNAME;uid=sa;pwd=PWD";
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
    cmd.CommandText = "select  name,data from [mongo] ";//SQL选择语句
    using (SqlDataReader reader = cmd.ExecuteReader())//执行sql语句
    {
         while (reader.Read())
         {
             StudentInfo stu = new StudentInfo();//实体类
             stu.name = reader["name"].ToString();
             stu.data = reader["data"].ToString()[0];
             stuList.Add(stu);
         }
     }
     string conn = "mongodb://localhost";
     string database = "mongotest";
     string collection = "mongo";
    // 连接数据库
     MongoServer mongodb = MongoServer.Create(conn); 
    // 选择数据库名
     MongoDatabase mongoDataBase = mongodb.GetDatabase(database); 
    // 选择集合,相当于表
     MongoCollection mongoCollection = mongoDataBase.GetCollection(collection); 
     mongodb.Connect();
     for (int i = 0; i < stuList.Count;i++ )
     {
          mongoModel he = new mongoModel();//实体类
          he.name = stuList[i].name;
          he.data = stuList[i].data;
          mongoCollection.Insert(he);//插入数据
     }
}

猜你喜欢

转载自blog.csdn.net/changeable0127/article/details/81185137