我希望你能帮我解决一些我已经搜索了很多次但还找不到答案的问题。正如问题的标题所述,我正在尝试在mySql数据库中创建一个表,其中我不知道列的数据类型。基本上,我使用php从csv文件在我的数据库中创建新的表。第一行包含列名。我知道这是可以做到的,因为我在phpMyAdmin中看到过,我可以选择一个csv文件并使用第一行来生成表列名称,而不必指定每一列的数据类型。
到目前为止,这是我的php代码:
$databaseName="myDatabase";
mysql_connect("localhost","xxxxxx","xxxxxxxx");
mysql_select_db($databaseName);
for($i = 0; $i < count($newFiles); $i++){//traverse the table that contains the file names
$content = file($newFileLocation.$newFiles[$i]);
//First line: $content[0];
$firstLine=$content[0];//save first line which are the column names
//echo $firstLine;
$tableName= str_replace('.txt','', $newFiles[$i]);//remove the .txt to use for table name
//echo $tableName."\n";
echo "\n\ncreating tables\n\n";
/*mysql_query("load data local infile '$newFiles[$i]'
into table $tableName
fields terminated by ','
lines terminated by '\n'
($firstLine) "); */
mysql_close();
}发布于 2012-04-23 01:36:02
以下是问题的解决方案。首先,我们取文件的第一行来保存cols名称(这样我们就知道如何创建表)。我们将其保存在一个字符串中,然后根据逗号字符将它们分开。在此之后,我们获取包含值的文件的第二行。我们将该行存储到一个字符串中,然后根据逗号字符将该字符串分隔为不同的值。我们将使用它来标识每个列的类型。
所以,这就是代码。
$databaseName="myDatabase";
mysql_connect("localhost","xxxxxx","xxxxxxxx");
mysql_select_db($databaseName);
for($k = 0; $k < count($newFiles); $k++){//traverse the table that contains the file names
$content = file($newFileLocation.$newFiles[$k]);
//First line: $content[0];
$firstLine=$content[0];
$secondLine=$content[1];
//echo $firstLine."\n";
$firstLine = str_replace("\r\n",'',$firstLine);
$colNames=explode(',',$firstLine);
$fieldList = explode(',',$secondLine);
$dataType="";
for($i = 0; $i < count($fieldList); $i++){
if (is_numeric($fieldList[$i])){
if (strpos($fieldList[$i],'.') == false){
$fieldList[$i] = (int)$fieldList[$i];
}else{
$fieldList[$i] = (float)$fieldList[$i];
}
}
switch(gettype($fieldList[$i])) {
case 'integer':
$typeInfo = 'int(11)';
break;
case 'float':
case 'double':
$typeInfo = 'float';
break;
case 'string':
$typeInfo = 'varchar(80)';
break;
default:
$typeInfo = 'varchar(80)';
break;
}
if(gettype($fieldList[$i]) != NULL) {
$dataType= $dataType.'`'.$colNames[$i].'` '." ".$typeInfo.' NOT NULL';
if(($i)!=count($fieldList)-1){
$dataType= $dataType.",";
}
}
} //end of for loop
$tableName= str_replace('.txt','', $newFiles[$k]);
//echo $tableName."\n";
//
//echo "\n".$dataType."\n";
$succ=mysql_query("CREATE TABLE `$tableName` ($dataType)");
if($succ)
echo "Table ".$tableName." was created Succesfully \n";
//echo $databaseName;
$loadsql = 'LOAD DATA LOCAL INFILE "'.$newFileLocation.$newFiles[$k].'" INTO TABLE `'.$tableName.'` FIELDS TERMINATED BY "," IGNORE 1 LINES ('.$firstLine.')';
mysql_query($loadsql);
}//end of for loop
mysql_close();发布于 2012-04-22 20:01:16
MySQL中没有“未知”的数据类型(可能blob类型与此最为相似)。
如果您真的只需要根据表字段的名称自动定义它们,并且不知道哪种类型的数据将存储在其中,那么可以将它们创建为blob或text,当在其中存储值时,可以创建一个由实际类型组成的文本表示形式,作为标题加上值的文本表示形式。
或者你根本不需要它。查看Using PHP to take the first line of a CSV file and create a MySQL Table with the data,也许你会在那里找到答案。
https://stackoverflow.com/questions/10266749
复制相似问题