C ++生成大量数据以输入SQL

时间:2013-11-13 14:14:38

标签: c++ sql database random populate

生成2个文件,其中1个包含用于存储到数据库中的数据,第二个文件包含将其上载到SQL所需的内容。代码没有编译,我不知道为什么。作为旁注:我正在上传10,000个一个关系,20000个另一个,200个另一个。

#include<iostream>
#include<fstream>
#include<cstdlib>

using namespace std;

int main()
{
    static const char alphanum[] =
    "0123456789"
    "!@#$%^&*"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz";
    int i;
    ofstream outFile;
    outFile.open("out.txt");

    for ( i = 1 ; i <= 30200 ; i++ )
{       
  if(i<=10000)
    outFile << rand() % 10  << "|" << alphanum[rand() % 8]<< "|" << alphanum[rand() % 10]<< "|" << rand() % 9 << "\n";

  else if(i>10000 && i<=30000)
    outFile << rand() % 11 << "|" << alphanum[rand() % 200] << "|" << rand() % 10  << "|" << rand() % 12 << "|" << "Nov 11 2013\n";
  else if(i>30000)
    outFile << rand() % 10 << "|" << alphanum[rand() % 8] << "\n";
}
    outFile.close("out.txt");

    outFile.open("populate.txt");
    for(i=1; i<=30200; i++)
      {
      if( i<=10000 )
        outFile << "LOAD DATA\n" << 
          "LOCAL INFILE "data/out.txt"\n" << 
          "REPLACE INTO TABLE Users\n" << 
          "FIELDS TERMINATED BY '|'\n"<<
          "(UserID, Username, Name, NOF);\n";

      else if ( i>10000 && i<=30000 )

        outFile >> "LOAD DATA\n"<< 
          "LOCAL INFILE "data/out.txt"\n" << 
          "REPLACE INTO TABLE Tweets\n" << 
          "FIELDS TERMINATED BY '|'\n" <<
          "(ID, Text, Length, Rating, Timestamp);\n";

      else if (i>30000)

        outFile  >> "LOAD DATA\n" << 
          "LOCAL INFILE "data/out.txt"\n" << 
          "REPLACE INTO TABLE Follows\n" << 
          "FIELDS TERMINATED BY '|'\n" <<
          "(UserID, Username);\n";
      }
    return 0;
}

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

问题在于,当您尝试写入<<时,您正在混合输出(>>)和输入(outFile)运算符。也就是说,您使用输入运算符而不是输出。

你也有这个问题

"LOCAL INFILE "data/out.txt"\n"

你不是说

"LOCAL INFILE data/out.txt\n"

"LOCAL INFILE \"data/out.txt\"\n"

或(知道SQL字符串是单引号)

"LOCAL INFILE 'data/out.txt'\n"

很明显,你刚刚完成了一些替换的复制粘贴,你可能想考虑制作一些将所有常用代码放在一个地方的东西,比如说一个函数?这样,当你改变公共代码时,你只需要在一个地方而不是多个地方(有可能忘记一个)。