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])]
Related
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
I have a Python string (or potentially a Python dictionary) that I'd like to insert to MySql table.
My String is the following:
{'ticker': 'BTC', 'avail_supply': 16479075.0, 'prices': 2750.99, 'name': 'Bitcoin', '24hvol': 678995000.0}
I have the same kind of error if I want to insert the Dict format.
I really don't understand this kind of error (i.e. the '\' in-between the components of the string).
How can I deal with this error? Any why to properly insert a whole string to a particular TEXT cell in SQL?
Many thanks !!
Here is how to connect, make a table, and insert in the table.
import MySQLdb as mdb
import sys
#connect
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
#need the cursor object so you can pass sql commands, also there is a dictionary cursor
cur = con.cursor()
#create example table
cur.execute("CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
#insert what you want
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
Example above will make a table with 2 cols, one ID and one name
look here on an example on how to insert stuff from dictionary with keys and list as value to sql, basically you need place holders
sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);"
data = {'qwe':1, 'asd':2, 'zxc':None}
conn = MySQLdb.connect(**params)
cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()
conn.close()
or you can go with this as an example for a simple straight forward dict
placeholders = ', '.join(['%s'] * len(myDict))
columns = ', '.join(myDict.keys())
sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, columns, placeholders)
cursor.execute(sql, myDict.values())
I am new to python and working on using the psycopg2 to insert data in postgres database. I am trying to insert items but get the error message
"Psycopg2.ProgrammingError: syntax error at or near "cup"
LINE 1: INSERT INTO store VALUES(7,10.5,coffee cup)
with the ^ next to coffee cup. I am assuming the order is wrong but i thought you could enter it this way as long as you specified the values.
Here is the code.
import psycopg2
def create_table():
conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert(quantity, price, item):
conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
cur=conn.cursor()
cur.execute("INSERT INTO store VALUES(%s,%s,%s)" % (quantity, price, item))
conn.commit()
conn.close()
create_table()
insert(7, 10.5, 'coffee cup')
Remember to always use the second argument of the execute command to pass the variables, as stated here.
Also, use the name of the fields in your syntax:
cur.execute("INSERT INTO store (item, quantity, price) VALUES (%s, %s, %s);", (item, quantity, price))
That should do the trick.
Problem in your case is coffee cup parameter value is considered as string but psycopg2 accept the value in single quote.
Basically as per my understanding when we create SQL query for psycopg2 it ask for single quote for data parameters [if you have given double quote for query start and end]
In your case you have given double quote for Query Start and end so you need to give single quote for the parameters.
My Observation is you provide single quote for each data paramater in psycopg2
import psycopg2
def create_table():
conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert(quantity, price, item):
conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
cur=conn.cursor()
#cur.execute("INSERT INTO store VALUES(%s,%s,%s)" % (quantity, price, item))
cur.execute("INSERT INTO store VALUES('%s','%s','%s')" % (quantity, price, item))
conn.commit()
conn.close()
create_table()
insert(7, 10.5, 'coffee cup')
I also faced the very same problem, and after a while troubleshooting the code, I found that I forgot to add commas(,) in the Insert query.
The code that causes the error:
data['query'] = 'insert into contacts (name, contact_no, alternate_contact_no, email_id, address)' \
'values (%s %s %s %s %s)'
As you can see in above code, I forgot to add commas after every '%s'.
The correct code:
data['query'] = 'insert into contacts (name, contact_no, alternate_contact_no, email_id, address)' \
'values (%s, %s, %s, %s, %s)'
Hope, It helps!
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))
I am trying to insert data into a PostgreSQL database table using Python. I don't see any syntax errors but, for some reason, my data isn't getting inserted into the database.
conn = psycopg2.connect(connection)
cursor = conn.cursor()
items = pickle.load(open(pickle_file,"rb"))
for item in items:
city = item[0]
price = item[1]
info = item[2]
query = "INSERT INTO items (info, city, price) VALUES (%s, %s, %s);"
data = (info, city, price)
cursor.execute(query, data)
You have to commit the transaction.
conn.commit()
If there's no reason to think the transaction will fail, it's faster to commit after the for loop finishes.