Error to view my data from database - python

I'm new in this python and mysql. I attempt to view the first row of data from my database. This is my code:
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="", # your passwords
db="58c_t2d_10") # name of the database
# you must create a Cursor object.
# It will let you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * 58c_10")
# print all the first cell of all the rows
for row in cur.fetchall() :
print row[0]
And I got this error:
OperationalError: (1044, "Access denied for user ''#'localhost'
to database '58c_t2d_10'")
I've tried to sign in as root:
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 '58c_10' at line 1")

cur.execute("SELECT * From 58c_10")
u have missed from

Related

Pymysql Programming Error "You have an error in your sql syntax"

I'm using Jupyter notebook to insert a pandas dataframe into a mysql table. But I can't execute the first SQL statement without getting this error: 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 'DROP TABLE IF EXISTS avila;CREATE TABLE avila( intercolumnar_distance FLOAT(12),' at line 1")
This is the code I am using to try to insert the dataframe 'avila'.
import pymysql
import pymysql.cursors as sql
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='')
curs = connection.cursor(pymysql.cursors.DictCursor)
# Create sql database for dataset
sql = 'DROP DATABASE IF EXISTS avila; CREATE DATABASE avila;'
curs.execute(sql)
sql = "USE avila;DROP TABLE IF EXISTS avila;CREATE TABLE avila( intercolumnar_distance FLOAT(12), upper_margin FLOAT(10), lower_margin FLOAT(10), exploitation FLOAT(10), row_num FLOAT(10), modular_ratio FLOAT(10), interlinear_spacing FLOAT(10), weight FLOAT(10), peak_number FLOAT(10), modratio_to_interlinspacing FLOAT(10), monk CHAR(5) );"
curs.execute(sql)
# Insert avila DataFrame into MySQL using sql alchemy
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://{user}:{pw}#localhost/{db}"
.format(user="root",
pw="XXXXX",
db="AVILA"))
avila.to_sql('avila', con = engine, if_exists = 'append')
I can't advance past the first sql statement because of the error.

ProgrammingError 1064 doing CREATE TABLE AS SELECT from an existing table with MySQL in Python

I have an existing table in the cloud and I want to make a copy of it. I connect to my database via pymysql, extract the username from an input provided from the new user, and I want to create a new table that will be called by the username, and that table will be a copy of the original one. When I run the code below, I have the following error:
pymysql.err.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 ''username' AS SELECT * FROM original_table' at line 1")
uname = blabla#bla.com
conn = pymysql.connect(
host="db.host",
port=int(3306),
user=user,
passwd=password,
db=db,
charset='utf8mb4'
)
cur = conn.cursor()
table_name = uname.replace('#', '_').replace('.', '_')
print('TABLE NAME:', table_name)
cur.execute(""" CREATE TABLE %s AS SELECT * FROM original_table """, (table_name))
Parameter quoting is for quoting values. Quoting table names does not work, because in MySQL the way to quote a table name is by using backticks (`), not quotation marks.
MariaDB [test]> CREATE TABLE 'username' AS SELECT * FROM my_table;
ERROR 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 ''username' AS SELECT * FROM my_table' at line 1
In this cause you need to use string formatting to create the SQL statement (you can use backticks to defend against SQL-injection*):
cur.execute(""" CREATE TABLE `%s` AS SELECT * FROM original_table """ % table_name)
* I'm not an expert on SQL-injection, so do some research if table_name originates outside your application.

how to insert filename as a string variable into mysql database in python

I have extracted filename from a certain directory. Filename is a string variable. Such as: 'LineNo-YYMMDD_hhmm'. Now I want to insert the filename into the existing MySQL DB. But couldn't find how to add as a str variable. This is what I had tried. Have some other way also checking net.
....
file_prefix = os.path.basename(name)[: - (len(filetail))]
(file_prefix is: LineName-200215_1619)
try:
connection = mysql.connector.connect(
host='localhost', db = 'db_name',
user='usr', password='myPass')
mysql_insert_query = " INSERT INTO fileHeader (headInfo) VALUES %s" % str(file_prefix)
cursor = connection.cursor()
cursor.execute(mysql_insert_query)
connection.commit()
cursor.close()
except mysql.connector.Error as error:
print ("Failed to insert record into fileHeader table {}".format(error))
Getting the following error:
Failed to insert record into fileHeader table 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
'LineName-200215_1619' at line 1
add '' in your mysql_insert_query:
mysql_insert_query = " INSERT INTO fileHeader (headInfo) VALUES ( '{0}')".format(file_prefix)

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)

How to fix "InterfaceError: No result set to fetch" from in python using mysql

I'm trying to run a select query in my already populated database through the mysql connector in python, and print the results.
I've checked the query "SELECT * FROM employee" in the mysql console and it works. I could not find an error in my code. Note that I can successfully insert rows into the database(so the credentials are correct). I looked around for a solution, but none of them were my exact problem. Here is my code:
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "....",
database = "officeplanning")
mycursor = mydb.cursor()
query = "SELECT * FROM employee"
mycursor.execute(query)
myresult = mycursor.fetchall()
for row in myresult: print(row)
I should be getting a list printed in the console, but instead I am getting the error:
File "C:\Users\Anubhab\Anaconda3\lib\site-packages\mysql\connector\cursor_cext.py", line 489, in fetchall
raise errors.InterfaceError("No result set to fetch from.")
InterfaceError: No result set to fetch from.
Edit: I did not call the fetchall() function twice (which caused the issue in that case) unlike the duplicate suggestion.

Categories

Resources