Connection of database using PyMySQL in Python 3.x - python

Getting connection error in PyMYSQL:
Error
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='pymysql')
AttributeError: 'module' object has no attribute 'connect'
code
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='pymysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
print(cur.description)
print()
for row in cur:
print(row)
cur.close()
conn.close()

Use capital 'C' in pymysql.Connect.
conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='', db='pymysql')
The above statement should work. It worked for me!

You've called some other module "pymysql". Look for a file named "pymysql.py" and rename it, and remove any associated .pyc file.

The connection was successful in this code:
con=pymysql.connect('localhost','root','root','mydb27')
But now I am following this code:
connection = pymysql.connect(host='localhost',
user='root',
password='kanha#12345',
database='mydb23',
charset='utf8mb4')
cur1=connection.cursor()
cur1.execute("select * from emp where city='hyd'")

I had that error, due I named my py file as select.py. I don't know how you named it but you could try changing the name file.

Related

print nothing after cursor of mysqldb

import pymysql
import MySQLdb
import MySQLdb.cursors
host="localhost"
user="nicola"
password="xxxxxx"
db="dbjud2"
conn = pymysql.connect(host=host,
user=user,
password=password,
db=db,
cursorclass=MySQLdb.cursors.DictCursor)
cursor = conn.cursor()
print(cursor)
cursor.execute("select * from annotation_web_server")
print("after cursor")
annotations = cursor.fetchall()
print("le annotazioni sono ",annotations)
This script simply execute a select.
My problem is that cursor seems not excute select query. It print nothing! In other words "after cursor" isn't print. Why?

Mysql with <User input> cant create table

Pythonista.
I am doing a Mysql database that first ask the user for the data base name. that works.
Once database is created it doest create the tables put prints out this error:
if not self._connection:
ReferenceError: weakly-referenced object no longer exists
Here is the code:
'''
import mysql.connector
# Create database
database_name = input(">> ")
db = mysql.connector.connect(
host='localhost',
user='root',
passwd='Mysql2021',)
my_cursor = db.cursor()
my_cursor.execute("CREATE DATABASE IF NOT EXISTS %s" %database_name)
db = mysql.connector.connect(
host='localhost',
user='root',
passwd='Mysql2021',
database=database_name)
# Create table
my_cursor.execute("CREATE TABLE test1 (firstname VARCHAR(255),lastname VARCHAR(255)")
'''
thank you for your help.
You are missing an opening bracket on the database name. It should ideally be like this:
my_cursor = db.cursor()
my_cursor.execute("CREATE DATABASE IF NOT EXISTS %s" %(database_name)
With the full code looking like this:
import mysql.connector
# Create database
database_name = input(">> ")
db = mysql.connector.connect(
host='localhost',
user='root',
passwd='Mysql2021',)
my_cursor = db.cursor()
my_cursor.execute("CREATE DATABASE IF NOT EXISTS %s" %(database_name)
db = mysql.connector.connect
host='localhost',
user='root',
passwd='Mysql2021',
database=database_name)
# Create table
my_cursor.execute("CREATE TABLE test1 (firstname VARCHAR(255),lastname VARCHAR(255)")

"AttributeError: __exit__" when importing data in SQL database

I am currently following alongside a book (cpp for quantitative finance) and I am trying to import the symbols for S&P500 from wiki into a sql database I've created. However, I am getting the AttributeError: exit with regards to my "with con" statement (see below). I have read posts from similar errors but I cannot seem to fix mine. I am extremely new to python so perhaps there is some fundamental misunderstanding on my part. I have included the relevant code below, any advice would be hugely appreciated.
"""
Insert the S&P500 symbols into the MySQL database.
"""
# Connect to the MySQL instance
db_host = 'localhost'
db_user = 'sec_user'
db_pass = 'database_password'
db_name = 'database_name'
con = mdb.connect(
host=db_host, user=db_user, passwd=db_pass, db=db_name
)
# Create the insert strings
column_str = """ticker, instrument, name, sector,
currency, created_date, last_updated_date
"""
insert_str = ("%s, " * 7)[:-2]
final_str = "INSERT INTO symbol (%s) VALUES (%s)" % \
(column_str, insert_str)
# Using the MySQL connection, carry out
# an INSERT INTO for every symbol
with con:
cur = con.cursor()
cur.executemany(final_str, symbols)
if __name__ == "__main__":
symbols = obtain_parse_wiki_snp500()
insert_snp500_symbols(symbols)
print("%s symbols were successfully added." % len(symbols))
The error is telling you that the object returned by mdb.connect is not a context manager, that is it cannot be used in a with statement. You'll need to close the connection manually once you've finished with it (con.close()) or use a package that provides a connection that is a context manager.
A quick study of commonly used connectors suggests you want to use pymysql
>>> import MySQLdb
>>> import mysql.connector
>>> import pymysql
>>> params = {'host': 'localhost', 'user': 'root', 'password': '', 'database': 'test'}
>>> for pkg in (MySQLdb, mysql.connector, pymysql):
... conn = pkg.connect(**params)
... try:
... with conn:
... pass
... except AttributeError as ex:
... print(pkg.__name__, 'failed with', ex)
...
MySQLdb failed with __enter__
mysql.connector failed with __enter__
If you have to use a connection that is not a context manager, you can emulate it in a try/except/finally suite:
import MySQLdb
conn = MySQLdb.connect(host='localhost', user='root', password='', database='test')
try:
cursor = conn.cursor()
cursor.execute('SELECT * FROM my_table;')
for row in cursor.fetchall():
print(row)
cursor.close()
conn.commit()
except:
# log the error here
conn.rollback()
finally:
conn.close()
Or you can make your own context manager using the tools provided in contextlib:
import contextlib
import MySQLdb
#contextlib.contextmanager
def managed_connection(conn):
try:
yield
conn.commit()
except:
# log the error here
conn.rollback()
finally:
conn.close()
conn = MySQLdb.connect(host='localhost', user='root', password='', database='test')
with managed_connection(conn) as mc:
cursor = mc.cursor()
cursor.execute('SELECT * FROM my_table;')
for row in cursor.fetchall():
print(row)
cursor.close()
(You can make a cursor context manager too, or have the context manager yield a cursor rather than the connection).

Python script unable to connect to MySQL db with no password

I am having a weird issue with my python script. My script has to connect to MySQL DB. This is the code:
try:
conn = MySQLdb.connect( user='root', host = 'localhost')
cursor = conn.cursor()
databases = cursor.fetchall()
cursor.close()
except Exception as e:
print e
when I run this script I have and error like:
(1045, "Access denied for user 'root'#'localhost' (using password: NO")
in the other hand, I can connect to MySQL just by entering MySQL (without password).
Why am I having this error with my python script when there is no password to root user?
Provide empty password
try this
conn = MySQLdb.connect( user='root', host = 'localhost', passwd='')
This should be the syntax. You should have the MySql connector for Python
import mysql.connector
cnx = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='database_name')
cnx.close()
try this (inside the bloc try except)
import mysql.connector
conn = mysql.connector.connect(user='root', password='',host='localhost',
database='your_database_name')
conn.close()

python MySQLdb error?

while i am trying to connect with python MySQLdb, i get an 'Invalid Arguments' error.
import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "",db = "test")
what is the reason for getting such a error?.
But, the following code with _mysql works fine.
db=_mysql.connect("localhost","root","","test")
import MySQLdb.cursors
DATABASE= MySQLdb.connect(host='localhost', user='username', passwd='password', db='databasename', cursorclass=MySQLdb.cursors.DictCursor)
Hope it helps.
Shouldn't that be
conn = MySQLdb.connect ("localhost","root","","test")
?
(random reference: http://www.tutorialspoint.com/python/python_database_access.htm )

Categories

Resources