I want to insert data to database table with these python 3 script,
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
for val in values:
cursor.execute(sql, params=val)
db.commit()
print("{} data ditambahkan".format(cursor.rowcount))
but I got error type "TypeError: execute() takes no keyword arguments". could someone help solve this error?
You can directly pass the query and values with it in the form of list.
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
for val in values:
cursor.execute(sql, list(val))
db.commit()
print("{} data ditambahkan".format(cursor.rowcount))
Or you can use executemany to insert all the values at one time.
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
cursor.executemany(sql, values)
db.commit()
print("{} data ditambahkan".for
Related
I have problem with storing values of a python dictionary as data to an existing mysql table
I tried to use the code below but it's not working.
db = mysql.connect(
host="localhost",
user="root",
passwd="123456",
database="tgdb"
)
cursor = db.cursor()
val = ', '.join("'" + str(x) + "'" for x in dict.values())
sql = "INSERT INTO tgdb.channel(user_name, image_url, name,
number_of_members, description, channel_url) VALUES (%s, %s, %s, %s, %s,
%s)"
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "record inserted.")
"you have an error in your SQL syntax"
As writed #Torxed shouldn't translate dict in string, you can write just that:
cursor.execute(sql, list(dict.values())
I have a table and I want to translate columns 'topic' and 'review' of a row and store the entire table with their translations into a new table. It seems that the for-loop doesn't iterate over all rows of the input table. Only the first row is stored into the new table. Why?
database = mysql.connector.connect(user='root', password='root', host='localhost', database='test')
DBcursor = database.cursor(buffered=True)
query = ("SELECT * FROM test_de")
DBcursor.execute(query)
for (id, user_name, date, country, version, score, topic, review, url) in DBcursor:
topic_trans = translate(topic, 'en')
review_trans = translate(review, 'en')
add_translation = ("INSERT INTO test_de_en(id, user_name, date, country, version, score, topic, review, url)"
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)")
translation_data = (id, user_name, date, country, version, score, topic_trans, review_trans, url)
DBcursor.execute(add_translation, translation_data)
database.commit()
DBcursor.close()
database.close()
I am trying to insert data to the table that was created earlier using python script. Here is the code I am trying to execute. I want to insert data into table with date as well.
date_today = dt.date.today()
conn = psycopg2.connect(host = serverip, port = port, database = database, user = uid, password = pwd)
cursor = conn.cursor()
cursor.execute("INSERT INTO My_TABLE (Date, Class, Total_students, failed_students, Percent_passed_students) VALUES (date_today, 'Class Name', int1, int2, int3)")
print "Data Inserted successfully"
conn.commit()
conn.close()
Here is the error I see from my job. what am i missing here?
psycopg2.ProgrammingError: column "date_today" does not exist
I created the table using different job with the following query:
cursor.execute("""CREATE TABLE MY_TABL(Date date, Lob varchar(30), Total_Students int, failed_students int, Percent_passed_students int)""")
And the table is created with above five columns.
This line:
cursor.execute("INSERT INTO My_TABLE (Date, Class, Total_students, failed_students, Percent_passed_students) VALUES (date_today, 'Class Name', int1, int2, int3)")
Is the incorrect way to dynamically insert values into a database.
Here's a functional and correct example:
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
And applying it in your case...
cursor.execute("INSERT INTO My_TABLE VALUES (%s, %s, %s, %s, %s)", (date_today, 'Class Name', int1, int2, int3))
cur1 = connection.cursor()
cur3 = connection.cursor()
cur3.execute("SELECT * FROM TABLE1")
connection.commit()
for i in range(0,totalRow-1):
row = cur3.fetchone()
if tempId.__contains__(row[0]):
cur1.execute("insert into summary (id, description, resolution) values (%s, %s, %s)",(row[0],row[1],tempResolution[tempId.index(row[0])]))
The above code is not giving any error but data is not inserting in the database.
instead of last line, try this:
tuple = row[0], row[1], tempResolution[tempId.index(row[0])]
cur1.executemany("insert into summary (id, description, resolution) values (?,?,?)", tuple)
if that doesn't work please expand your code explaining what are totalRow, tempId.__contains__ and types of row[0],row[1],tempResolution[tempId.index(row[0])]
I have a simple registration form which creates a new record in "Students" table:
cur = con.cursor()
query = "INSERT INTO students (Name, Address, Major, Phone, Email, Password) values (%s, %s, %s, %s, %s, %s)"
args = [name, address, major,phone, email, password]
cur.execute(query, args)
con.commit()
The column Id is auto-incremented, so in order to get the last Id, I select Max
query = "SELECT MAX(Id) FROM students;"
cur.execute(query)
id = cur.fetchone()[0]
It works in my little homework-project, but how would it be done in a heavy-loaded project, where there is a possibility of something being created before the select statement?
Use lastrowid attribute:
...
cur.execute(query, args)
id = cur.lastrowid