Facing issues in Python to MYSQL insertion - python

I've tried to use couple of methods to insert data into mysql database but getting error in all:
In the first method:
sql = ('''Insert into lgemployees (EmpID,Name,Gender,DOB,Address,PhoneNumber,Email)
VALUES (%d,$s,$s,$s,$s,$d,$s)''', (eid, name, gen, dob, add, mob, email))
mycursor.execute(sql)
mycursor.commit()
Error in this approach:
'tuple' object has no attribute 'encode'
2nd method:
sql = "Insert into lgemployees (EmpID,Name,Gender,DOB,Address,PhoneNumber,Email) VALUES(?,?,?,?,?,?,?,)"
val = (eid, name, gen, dob, add, mob, email)
mycursor.execute(sql, val)
mycursor.commit()
Error in this approach :
"Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
I've troubleshooted a lot from my end but no luck. Can any one please help as where am I wrong or what else can be a good option to insert data into mysql from python.

I dont know where you error is at, but ive tested with this code and it works.
insert_tuple = (eid, name, gen, dob, add, mob, email)
sql = """INSERT INTO lgemployees (`EmpID `,
`Name`,`Gender`, `DOB`, `Address`, `PhoneNumber`, `Email`)
VALUES (%s,%s,%s,%s,%s,%s,%s)"""
mycursor = mySQLconnection.cursor()
mycursor.execute(sql, insert_tuple)
mySQLconnection.commit()
mycursor.close()
your code throws this because one of the parameters are empty or are in a format it cant read.
"Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

Related

Save resulting dict from api into db - psycopg2

I want to save an API response, on some table of my database, I'm using Postgres along with psycopg2.
This is my code:
import json
import requests
import psycopg2
def my_func():
response = requests.get("https://path/to/api/")
data = response.json()
while data['next'] is not None:
response = requests.get(data['next'])
data = response.json()
for item in data['results']:
try:
connection = psycopg2.connect(user="user",
password="user",
host="127.0.0.1",
port="5432",
database="mydb")
cursor = connection.cursor()
postgres_insert_query = """ INSERT INTO table_items (NAME VALUES (%s)"""
record_to_insert = print(item['name'])
cursor.execute(postgres_insert_query, record_to_insert)
connection.commit()
count = cursor.rowcount
print (count, "success")
except (Exception, psycopg2.Error) as error :
if(connection):
print("error", error)
finally:
if(connection):
cursor.close()
connection.close()
my_func()
I mean, I just wanted to sort of "print" all the resulting data from my request into the db, is there a way to accomplish this?
I'm a bit confused as You can see, I mean, what could be some "print" equivalent to achieve this?
I mean, I just want to save from the API response, the name field, into the database table. Or actually INSERT that, I guess psycopg2 has some sort of function for this circumstance?
Any example You could provide?
EDIT
Sorry, I forgot, if I run this code it will throw this:
PostgreSQL connection is closed
A particular name
Failed to insert record into table_items table syntax error at or near "VALUES"
LINE 1: INSERT INTO table_items (NAME VALUES (%s)
There are a few issues here. I'm not sure what the API is or what it is returning, but I will make some assumptions and suggestions based on those.
There is a syntax error in your query, it is missing a ) it should be:
postgres_insert_query = 'INSERT INTO table_items (NAME) VALUES (%s)'
(I'm also assuming thatNAME` is a real column in your database).
Even with this correction, you will have a problem since:
record_to_insert = print(item['name']) will set record_to_insert to None. The return value of the print function is always None. The line should instead be:
record_to_insert = item['name']
(assuming the key name in the dict item is actually the field you're looking for)
I believe calls to execute must pass replacements as a tuple so the line: cursor.execute(postgres_insert_query, record_to_insert) should be:
cursor.execute(postgres_insert_query, (record_to_insert,))

How can I store a string with mixed quotes in a Sqlite database using python?

I have a string with mixed quotes that is " and '. I want to store the string in a Text field in a sqlite3 database using python.
Here is the query I'm using and I have a function that executes these queries.
"""INSERT INTO SNIPPETS (CONTENT, LANGUAGE, TITLE, BACKGROUND)
VALUES("{0}" ,"{1}","{2}", "{3}")
""".format(content, language, title, background)
Something like:
with self.connection as conn:
cursor = conn.cursor()
try:
result = cursor.execute(statement)
if(insert_operation):
return cursor.lastrowid
return result.fetchall()
You don't have to make it too complicated. Python sqlite3 will take care of the quoting for you.
statement = 'INSERT INTO SNIPPETS (CONTENT, LANGUAGE, TITLE, BACKGROUND) VALUES (?, ?, ?, ?)'
cursor.execute(statement, (content, language, title, background))

Insert query with variables postgresql python

I'm trying to insert several variables in a insert query on postgres using python. I can't wrap my head around how to use the string formatting.
For example, this works fine:
cursor.execute('''CREATE TABLE %s
(id SERIAL PRIMARY KEY,
sender varchar(255) not null,
receiver varchar(255) not null,
message varchar(255))''' %username)
as does this:
cursor.execute('''INSERT INTO test (sender, receiver, message)
VALUES(%s,%s,%s)''', (sender, receiver,message))
My problem is that I want to have the table name as a variable too. I have tried:
cursor.execute('''INSERT INTO %s (sender, receiver, message)
VALUES(%s,%s,%s)''' %username, (sender, receiver, message))
I get the following error:
TypeError: not enough arguments for format string
I get that I have to change the parentheses somehow, but I don't know how.
Thanks in advance.
EDIT:
Choose a different approach from this psycopg2 which worked perfectly.
You are passing the arguments in a wrong way. The arguments passed are causing you the trouble. Use format function instead of % as it is more sophisticated and readable.
"INSERT INTO {} (sender, receiver, message) VALUES({},{},{})".format("some", "world", "world","hello")
The output of the above:
'INSERT INTO some (sender, receiver, message) VALUES(world,world,hello)'
Use the high level sql module to avoid likely mistakes:
from psycopg2 import sql
query = sql.SQL('''
insert into {} (sender, receiver, message)
values (%s, %s, %s)
''').format(sql.Identifier(username))
cursor.execute (query, (sender, receiver, message))

Psycopg2 issue inserting values into an existing table in the database

I am having a hard time understanding why psycopg2 has a problem with the word 'user'. I am trying to insert values into a table called user with the columns user_id, name, password. I am getting a programmingError: syntax error at or near "user". open_cursor() is a function used to open a cursor for database operations.
Here is my code:
query = """INSERT INTO user (name, password) VALUES (%s, %s);"""
data = ('psycouser', 'sha1$ba316b$52dd71da1e331247f0a7ab869e1b072210add9c1')
with open_cursor() as cursor:
cursor.execute(query, data)
print "Done."
because user is a part of sql language.
try taking it in dbl quotes:
query = 'INSERT INTO "user" (name, password) VALUES (%s, %s);'

Python MySQLdb failing to insert

I'm trying
title = "Title here"
url = "http://www.mysite.com/url-goes-here"
cursor.execute("""INSERT INTO `videos_justicevids` (`title`, `pageurl`) VALUES (%s, %s)""",(title, url))
I'm not getting an error, but it's not inserting into the database.
You need to commit it.
connection.commit()

Categories

Resources