Accessing MySQL from Python 2.7: ProgrammingError: 1045 (28000) - python

I am having difficulties connecting to a MySQL database using Python 2.7. The error I'm getting is
ProgrammingError: 1045 (28000): Access denied for user
'tommyan'#'localhost' (using password: YES)
I know similar questions exist, but none of those were helpful to me. My code is below, thanks in advance.
import mysql.connector
mydb = mysql.connector.connect(
host="127.0.0.1",
user="tommyan",
passwd="######",
database="mydatabase"
)
mycursor = mbdb.cursor()
sql = "INSERT INTO places (name, desc) VALUES (%s, %s)"
val = ("Natinal gallery", "Housing masterpieces by painters including van Gogh,
Renoir, da Vinci and Michelangelo")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

Related

How to insert variable to mysql database with python? "You have an error in your SQL syntax"

I am trying to insert one variable to mysql database with python. But I have syntax error.. Can You help me please? :)
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='localhost',
database='Xiaomi_Temp',
user='user',
password='pass')
cursor = connection.cursor()
mySql_insert_query = """ INSERT INTO Temp_test (batt) VALUES (%d) """
recordTuple = (batt)
print(batt)
cursor.execute(mySql_insert_query, recordTuple)
connection.commit()
print("Record inserted successfully into table")
cursor.close()
except mysql.connector.Error as error:
print("Failed to insert record into table {}".format(error))
finally:
if (connection.is_connected()):
connection.close()
print("MySQL connection is closed")
I have variable batt and it has integer value.
My output is:
Failed to insert record into table 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%d)' at line 1
MySQL connection is closed
As the whole query needs to be in a string format while execution of query so %s should be used instead of %d which can be done as follows,
mySql_insert_query = """ INSERT INTO Temp_test (batt) VALUES (%s) """
recordTuple = (batt)
print(batt)
cursor.execute(mySql_insert_query, recordTuple)

Insert into MySQL table with Python

I am trying to insert basic data into my MySQL table without any success yet I'm using basic tutorials as demos.
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1
My MySQL
CREATE TABLE awesome (
id int NOT NULL AUTO_INCREMENT,
test varchar(50),
PRIMARY KEY (id)
);
My Python code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="pass",
database="db"
)
mycursor = mydb.cursor()
sql = "INSERT INTO awesome (test) VALUES (%s)"
val = ("Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Yes the problem arises when there is only 1 argument in val tuple. Use
val=("Highway 21",)
Note the comma at the end.

How to intsert quotation mark `'` into mariaDB using mysql-client?

I am using mariaDB(Ver 15.1 Distrib 10.0.17-MariaDB, for osx10.10 (x86_64)) and mysqlclient==1.3.6.
I just want to insert a string into a varcharfield.
import MySQLdb
import json
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='',
db='ng')
cur = conn.cursor()
cur.execute(INSERT INTO `current_table` (`id`, `name`) VALUES (NULL, '{name}');".format(name="Lily' dog"))
conn.commit()
but I always got a error like this:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's dog', NULL)' at line 1")
what should I do if I want to insert quotation mark by mysql-client?
According to Amadan's comment, in bobby-tables(the site for preventing SQL injections), it suggest:
Using the Python DB API, don't do this:
Do NOT do it this way:
cmd = "update people set name='%s' where id='%s'" % (name, id)
curs.execute(cmd)
Instead, do this:
cmd = "update people set name=%s where id=%s"
curs.execute(cmd, (name, id))
so in my situation, just modify the execute line to :
cmd = "INSERT INTO `current_table` (`id`, `name`) VALUES (NULL, %s);"
cur.execute(cmd, ("Lily's dog"))
and this can avoid the error which quotation mark leads to.

AttributeError: 'MySQLCursor' object has no attribute 'commit'

def fillblast(sequentie, titel_lijst, score_lijst, e_lijst, iden_lijst, pos_lijst, gaps_lijst):
conn = mysql.connector.connect(host = "ithurtswhenip.nl", user = "pg2", password = "pg2", database= "pg2", port= "3307")
cursor = conn.cursor()
Blast = 1000
for i in range(0,len(titel_lijst)):
Blast =+ 2
cursor.execute("INSERT INTO `pg2`.`Blast` (`Blast_id`, `Blast_seq`, `Blast_titel`, `Blast_score`, `Blast_E`, `Blast_gaps`, `Blast_pos`, `Blast_iden`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);", (Blast, sequentie[i] ,titel_lijst[i], score_lijst[i], e_lijst[i], iden_lijst[i], pos_lijst[i], gaps_lijst[i]))
print("1 record toegevoegd")
cursor.commit()
cursor.close()
conn.close()
I get the following error:
AttributeError: 'MySQLCursor' object has no attribute 'commit'
How does it come, and where does it go wrong?
I try to connect with MySQLWorkbench.
EDIT:
Now I get the following error:
mysql.connector.errors.DatabaseError: 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
Because you can not commit a cursor! you must commit the connection.
# cursor.commit() --> This is wrong!
conn.commit() # This is right
Check the docs...
While fixing some legacy code (that apparently hasn't been working for a couple of years, so users stopped trying to use it), we ran into the same error, using the MySQL-python package in Django. Using the suggestions on this and other answers however resulted in a different error, on account of it occurring within the Django ORM:
django.db.transaction.TransactionManagementError: This code isn't
under transaction management
So for those who run into this error after using conn.commit() instead of cursor.commit(), you may be able to use enter_transaction_management and leave_transaction_management (note that this was for Django 1.4.6 and MySQL-python 1.2.5; I may have to update this once we get the Django upgrade completed):
try:
conn.enter_transaction_management()
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
except DatabaseError as e:
cursor.rollback()
log.warning('log warning here')
# Handle other exceptions here.
finally:
if cursor:
cursor.close()
conn.leave_transaction_management()

pywhois parsed results into mysql

sorry if you consider as repost, quite simple code and i suspect also a trivial error here, but can't move forward:
import whois
import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", passwd="pass", db="whois")
cur = db.cursor()
wi = whois.whois("google.com")
cur.execute("""INSERT INTO wrec (dname, wfull, dns) VALUES (%s, %s, %s)""") , (wi.domain_name, wi.text, wi.name_servers)
ends up in:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s, %s, %s)' at line 1")
as said, suspecting trivial error. any suggestions? thanks a lot in advance
You placed the fetched Whois variables outside the execute function!
Change:
cur.execute("""INSERT INTO wrec (dname, wfull, dns) VALUES (%s, %s, %s)""") , (wi.domain_name, wi.text, wi.name_servers)
To:
cur.execute("""INSERT INTO wrec (dname, wfull, dns) VALUES (%s, %s, %s)""", (wi.domain_name, wi.text, wi.name_servers))
Edit:
And don't forget to add:
db.commit()
at the end of the script.

Categories

Resources