我在PostgreSQL中有两个通过pgAdmin4创建的简单表:
表1:
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom')
->add('categorie', EntityType::class, [
'class' => 'App\Entity\Categorie',
//'placeholder' => '',
])
;
$formModifier = function (FormInterface $form, Categorie $categorie = null) {
$subcategories = null === $categorie ? [] : $categorie->getSubcategories();
//var_dump($subcategories);
$form->add('subcategorie', EntityType::class, [
'class' => 'App\Entity\Subcategorie',
//'placeholder' => '',
'choices' => $subcategories,
]);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
// this would be your entity
$data = $event->getData();
//var_dump($data);
//die;
$formModifier($event->getForm(), $data->getCategorie());
}
);
$builder->get('categorie')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$categorie = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $categorie);
}
);
//...
}
表2:
CREATE TABLE public.table1
(
id serial,
name text,
PRIMARY KEY (id)
)
使用外键创建第二个表并引用第一个表后,table1中的数据类型id会自动更改为整数:
如果我尝试手动将类型更改为串行,则找不到它。
并且还使用psycopg2进行此插入:
CREATE TABLE public.table2
(
fk_id integer,
name text,
PRIMARY KEY (name),
CONSTRAINT fk FOREIGN KEY (fk_id)
REFERENCES public.table1 (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
但是这个失败了:
connection = psycopg2.connect(user = "user",
password = "pass",
host = "localhost",
port = "5432",
database = "db")
cursor = connection.cursor()
postgres_insert_query = """INSERT INTO table1 (id,name) VALUES (%s,%s)"""
record_to_insert = (1,'sometext')
cursor.execute(postgres_insert_query, record_to_insert)
connection.commit()
打印此错误:“并非在格式化字符串时转换了所有参数”
答案 0 :(得分:0)
我只是错过了@Jeremy注释的逗号
record_to_insert = ('sometext',)