Python scraper how to add mysql insert - python

What is wrong in my code ? I want to add %s to my mysql db.
titlux = tree.xpath('//*[#id="offer-title"]/h1/text()')
pretx = tree.xpath('//*[#id="offer-price-stock"]/div[3]/span/#content')
print "%s," % titlux
print "%s," % pretx
print "\n"
conn = ..............
x = conn.cursor()
try:
x.execute ("""INSERT INTO produse (titlu, pret) VALUES (%s, %s)""")
conn.commit()
except:
conn.rollback()
conn.close()

You're missing the replacement variables and some quotes in your SQL insert. Change it to:
x.execute ("""INSERT INTO produse (titlu, pret) VALUES ("%s", "%s")""" % (titlux[0], pretx[0]))

#Alastair has the right answer but if you want to see the query you're using
print "INSERT INTO produse (titlu, pret) VALUES (%s, %s)" % (titlux, pretx)
x.execute ("""INSERT INTO produse (titlu, pret) VALUES (%s, %s)""" % (titlux, pretx))

Related

Getting InternalError: Unread result found after inserting new data

I'm new to python and MySQL but I've been trying to program a schema which has a user entity with 2 subtypes: student and instructor. When I use this function
def create_user(userName, email, Instructor):
mycursor = mydb.cursor()
generatedKey = uuid.uuid4()
id = generatedKey.bytes
generatedKey = uuid.uuid4()
PCID = generatedKey.bytes
sql = "INSERT INTO User(UserID,UserName, UserEmail) VALUES (%s, %s, %s)"
val = (id, userName, email)
mycursor.execute(sql, val)
mydb.commit()
if(Instructor):
sql = "INSERT INTO PostCreator(PCID, CreatorType) VALUES (%s, %s)"
val = (PCID, "Instructor")
mycursor.execute(sql, val)
mydb.commit()
sql = "INSERT INTO Instructor(InstructorId,PCID) VALUES (%s, %s)"
val = (id, PCID)
mycursor.execute(sql, val)
mydb.commit()
else:
sql = "INSERT INTO PostCreator(PCID, CreatorType) VALUES (%s, %s)"
val = (PCID, "Student")
mycursor.execute(sql, val)
mydb.commit()
sql = "INSERT INTO Student(StudentId,PCID) VALUES (%s, %s)"
val = (id, PCID)
mycursor.execute(sql, val)
mydb.commit()
print("Registered", userName)
to create a student I don't have any issues. However when I try to create an instructor the system either times out, or creates an instructor but and following calls on the system results in a: InternalError: Unread result found after inserting new data.
I have no idea why making a student is ok but instructors don't work. Their tables are created the same in the SQL.

Python Sql İmport Data String

I can't enter data into sql. I tried everything but i get this error.
x.execute (" INSERT INTO ords VALUES ('%s', '%s' '%s')" %'f' %'test' %'try' ) TypeError: not enough arguments for format string
import mysql.connector`enter code here`
conn = mysql.connector.connect(user='root', password='1234', host='localhost', database='neworder')
x = conn.cursor()
x.execute("SELECT * FROM ords")
x.execute (" INSERT INTO ords VALUES ('%s', '%s' '%s')" %'f' %'test' %'try' )
conn.commit()
conn.close()

Python sql statement error

I've run into a problem while trying to execute an insert statement from python.
Here is my function definition:
def fill_course(param_string):
ar = param_string.split("|")
db = connect()
sql = (
"INSERT INTO COURSE(`NAME`, `DURATION`, `DEPT`) "
"VALUES (%s, %s, %s)"
)
data = ar[0], ar[1], ar[2]
cursor = db.cursor()
cursor.execute(sql, data)
db.commit()
if cursor.rowcount == 0:
res = 0
elif cursor.rowcount == 1:
res = 1
db.close()
print(res)
return res
I've followed this link as a reference.
The error I am getting is :
File "database.py", line 25
"INSERT INTO COURSE "VALUES (%s, %s, %s)"
^
SyntaxError: invalid syntax
I am not able to understand which part of the syntax is wrong here?
Please write the following string
"INSERT INTO COURSE(`NAME`, `DURATION`, `DEPT`) "
"VALUES (%s, %s, %s)"
like below:
"INSERT INTO COURSE(`NAME`, `DURATION`, `DEPT`) VALUES (%s, %s, %s)"
or concatenate the two strings. As it is now, there is a syntax error.

Inserting an array into mysql with Python

I am building this array with 40k entries.
array = [(value1, value2, value3),(value1, value2, value3),(value1, value2, value3) .... ]
Is it possible to insert this into mysql in python something like:
cursor.execute('''INSERT IGNORE into %s VALUES *array here*''' % (table_name, array))
I am having trouble passing the array variable into mysql correctly. Any help appreciated.
Yes you can do it with executemany:
cursor.executemany('INSERT IGNORE into %s VALUES(%s, %s, %s)'%table_name, sql_data)
Note: you shouldn't use % to pass values to the database, instead you need to pass them in the second parameter of execute/executemany. i used % for the table name because the first parameter is the prepared query string.
This is Use for me try it.
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="test"
)
mycursor = mydb.cursor()
print("Insert Process... Please Wait...")
for r in range(1,tdrows+1):
a = []
for c in range(1,tdcols+1):
a.append(driver.find_element_by_xpath("//*[#id='DataTables_Table_0']/tbody/tr["+str(r)+"]/td["+str(c)+"]").text)
sql = "INSERT IGNORE into test_table(id,fname,lname) VALUES (%s, %s, %s)"
val = (a)
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "Record Inserted.")

data is not inserting in my table

import MySQLdb
import csv
mydb = MySQLdb.connect(host='localhost',user='root',passwd='root', db='kabir')
cursor = mydb.cursor()
data = csv.reader(file('data.csv'))
#cursor.execute('create table actors(name varchar(20),age integer)')
for row in data:
cursor.execute('INSERT INTO actors(name,age) VALUES(%s %s)' ,row)
mydb.commit()
cursor.close()
You didn't specify a comma between %s and %s. Change it to:
cursor.execute('INSERT INTO actors(name,age) VALUES(%s, %s)' ,row)
and try..

Categories