Inserting two tables with many-to-many relationship in a single for loop using pandas on MariaDB
P粉710478990
2023-08-15 12:18:58
<p>我正在嘗試批量插入數(shù)據(jù)到兩個(gè)具有多對(duì)多關(guān)系的表中,如果我只在一個(gè)表中插入沒有問題,但我無法同時(shí)在兩個(gè)表中插入。</p>
<pre class="brush:php;toolbar:false;">CREATE TABLE IF NOT EXISTS `mydbv3`.`PRODOTTI` (
`idPRODOTTI` INT(11) NOT NULL AUTO_INCREMENT,
`PROD_ATTIVO` TINYINT(4) NULL DEFAULT 1,
`EAN13` VARCHAR(45) NOT NULL,
`prod_nome` VARCHAR(300) NOT NULL,
`Prezzo` DECIMAL(15,2) NULL DEFAULT NULL,
`Costo` DECIMAL(15,2) NOT NULL,
`PRODOTTI_marca` VARCHAR(45) NULL DEFAULT NULL,
`Quantita` DECIMAL(10,0) NOT NULL DEFAULT 0,
`PRODOTTI_descrizione` TEXT NULL DEFAULT NULL,
`Data_ins` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP(),
`Data_update` TIMESTAMP NULL DEFAULT NULL,
`CheckProd` TIMESTAMP NULL DEFAULT NULL,
`Fornitori_Ordini_idOrdini` INT(11) NULL DEFAULT NULL,
`Fornitori_idFornitori` INT(11) NOT NULL,
`CAT_IVA_idCAT_IVA` INT(11) NOT NULL,
PRIMARY KEY (`idPRODOTTI`),
UNIQUE INDEX `idPRODOTTI_UNIQUE` (`idPRODOTTI` ASC) VISIBLE,
INDEX `fk_PRODOTTI_Fornitori1_idx` (`Fornitori_idFornitori` ASC) VISIBLE,
INDEX `fk_PRODOTTI_CAT_IVA1_idx` (`CAT_IVA_idCAT_IVA` ASC) VISIBLE,
CONSTRAINT `fk_PRODOTTI_CAT_IVA1`
FOREIGN KEY (`CAT_IVA_idCAT_IVA`)
REFERENCES `mydbv3`.`CAT_IVA` (`idCAT_IVA`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_PRODOTTI_Fornitori1`
FOREIGN KEY (`Fornitori_idFornitori`)
REFERENCES `mydbv3`.`Fornitori` (`idFornitori`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 145908
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `mydbv3`.`CATEGORIE` (
`idCATEGORIE` INT(11) NOT NULL AUTO_INCREMENT,
`Nome_Categoria` VARCHAR(45) NOT NULL,
`Categoria_Padre` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idCATEGORIE`))
ENGINE = InnoDB
AUTO_INCREMENT = 31
DEFAULT CHARACTER SET = utf8;</pre>
<p>這是我嘗試的代碼</p>
<pre class="brush:php;toolbar:false;">import pandas as pd
import mysql.connector as msql
from mysql.connector import Error
empdata = pd.read_csv('static/files/prod_ridotto3.csv', index_col=False, delimiter=';', on_bad_lines='skip', usecols=["Attivo (0/1)","EAN13","Nome","Categorie","Prezzo","IVAID","Costo","Fornitore","Quantità","Data Ordine"])
#print(empdata.head())
#cat = series_one = pd.Series(empdata.Age)
#EANDATA = pd.read_csv('static/files/prod_ridotto3.csv', delimiter=';', on_bad_lines='skip', usecols=["Categorie"])
#print (EANDATA)
#print(EANDATA.head())
try:
conn = msql.connect(host='192.168.1.2', database='mydbv3', user='root', password='password')
try:
if conn.is_connected():
cursor = conn.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
#print (record)
print("You're connected to database: ", record)
#loop through the data frame
for i,row in empdata.iterrows():
sql = "INSERT INTO PRODOTTI (PROD_ATTIVO,EAN13,prod_nome,Prezzo,CAT_IVA_idCAT_IVA,Costo,Fornitori_idFornitori,Quantita,Data_ins)
VALUES (%s,%s,%s,%s,(select idCAT_IVA from CAT_IVA where CAT_IVA_code = %s),%s,
(select idFornitori from Fornitori where FORNITORI_Nome = %s),%s,%s)"
#print (type(row))
#print(row)
#print(tuple(row))
cat = (row.Categorie,)
#print("Type CAT",type(cat))
#print("CAT=",cat)
#print (type(tuple(cat)))
sql1 = "INSERT INTO PRODOTTI_has_CATEGORIE (PRODOTTI_idPRODOTTI,CATEGORIE_idCATEGORIE) VALUES ((SELECT LAST_INSERT_ID()),(select CATEGORIE.idCATEGORIE from CATEGORIE where Nome_Categoria = %s))"
cursor = conn.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print (record)
#print(sql)
#print(tuple(row))
#print(row)
cursor.execute(sql, tuple(row))
cursor.execute(sql1, cat)
print("Product inserted",i)
conn.commit()
except Error as e:
print("Error while inserting in DB", e)
except Error as e:
print("Error while connecting to MySQL", e)</pre>
<p>現(xiàn)在,顯然我會(huì)得到錯(cuò)誤:<code>AttributeError: 'Series' object has no attribute 'Categorie'</code>
但是如果我在</p>
<pre class="brush:php;toolbar:false;">usecols=["Attivo (0/1)","EAN13","Nome","Categorie","Prezzo","IVAID","Costo","Fornitore","Quantità","Data Ordine"])</pre>
<p>然后我在第一個(gè)插入中沒有用到它,會(huì)出現(xiàn)與未使用所有字段相關(guān)的錯(cuò)誤。</p>
<p>我認(rèn)為一定存在一個(gè)簡(jiǎn)單的解決方案,或者我的數(shù)據(jù)庫結(jié)構(gòu)存在問題。
我嘗試了很多不同的方法,但都沒有成功,有人可以幫助解決這個(gè)問題嗎?</p>
<p>謝謝。</p>
If I understand correctly, the following lines of code:
cat = (row.Categorie,)
Creates a tuple with only one value.
Then, use this statement to provide a tuple with only one value:
cursor.execute(sql1, cat)
But actually you should provide more values.
So you need to check this line of code and provide all the values ??required by sql1.
Hope it helps you.
Like +0
P粉710478990