我想将数据从JSON文件导入数据库表。我将条令与pdo_sqlite驱动程序一起使用,并配置了以下实体:
/**
* @Entity @Table(name="mytable")
**/
class MyClass
{
/** @Id @Column(type="integer") @GeneratedValue *
* @Column(type="integer")
*/
var $id;
/** @Column(type="string") **/
var $name;
/** @Column(type="simple_array") **/
var $parameters;
function __construct($name, $parameters)
{
$this->name = $name;
$this->parameters = $parameters;
}
// getters and setters here
}
我创建了一个简单的导入方法:
function importFromJson($tableName, $fileName)
{
if (file_exists($fileName)) {
$data = json_decode(file_get_contents($fileName));
if (is_array($data)) {
$connection = getEm()->getConnection();
foreach($data as $tuple) {
if (is_object($tuple)) {
$connection->insert($tableName, (array)$tuple);
}
}
}
}
}
我的进口。json文件包含以下文本:
[
{
"name": "A name",
"parameters": ["a","b","c"]
}
]
调用导入方法时:
importFromJson("mytable", "import.json");
我得到以下错误:
执行INSERT INTO mytable(name,参数)VALUES时发生异常 (?, ?)'用参数["A name",["a","b","c"]]:
数组到字符串转换C:\myproject\供应商\原则\dbal\lib\原则\DBAL\DBALException.php:119C:\myproject\供应商\原则\dbal\lib\原则\DBAL\Connection.php:996C:\myproject\供应商\原则\dbal\lib\原则\DBAL\Connection.php:696C:\myproject\lib\import.php:39
simple_array类型的确切目的不是将数组转换为可以存储在数据库中的字符串吗?
我不知道为什么你必须像在数据库中存储数组一样存储参数,但是一个简单的方法是先存储它,你应该把参数
转换成一个有效的字符串,否则它就不能正确存储。
foreach($data as $tuple) {
if (is_object($tuple)) {
$touple = implode(",", (array)$touple);
$connection->insert($tableName, (array)$tuple);
}
}
另一个选项是将其转换为json字符串
foreach($data as $tuple) {
if (is_object($tuple)) {
$touple = json_encode($touple);
$connection->insert($tableName, (array)$tuple);
}
}
为了能够在使用选择
时使用数据,您应该再次使用爆炸()
或json_encode
将数据转换回数组。希望这个炒锅!:)