print nothing after cursor of mysqldb - python

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?

Related

In Pycharm editor MySQL Command "Show databases " not returning results nor error after run?

After running the following code, no results are coming from the MySQL command:
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",password="Abhi#123")
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
Take a look at this answer: https://stackoverflow.com/a/20959654/7420301
Maybe try something like this...
import mysql.connector mydb = mysql.connector.connect(host="localhost",
user="root",
password="Abhi#123")
try:
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
all_my_databases = mycursor.fetchall()
print all_my_databases
finally:
mydb.close()

"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).

How to connect to Oracle DB through python

I am trying to connect to Oracle through Python and trying to execute a few DDL & DML statements. Please help how it can be done
a simple query
import cx_Oracle
con = cx_Oracle.connect('pythonhol/welcome#127.0.0.1/orcl')
cur = con.cursor()
cur.execute('select * from departments order by department_id')
for result in cur:
print result
cur.close()
con.close()
You can do something like this:
import cx_Oracle
connection = cx_Oracle.connect("username", "password", "ip of your server"/"database name")
cursor = connection.cursor()
cursor.execute("select * from table_name")
for row in cursor:
print(row)
connection.close()

Connection of database using PyMySQL in Python 3.x

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.

About MySQLdb conn.autocommit(True)

I have installed python 2.7 64bit,MySQL-python-1.2.3.win-amd64-py2.7.exe.
I use the following code to insert data :
class postcon:
def POST(self):
conn=MySQLdb.connect(host="localhost",user="root",passwd="mysql",db="dang",charset="utf8")
cursor = conn.cursor()
n = cursor.execute("insert into d_message (mid,title,content,image) values(2,'xx','ccc','fff')")
cursor.close()
conn.close()
if n:
raise web.seeother('/')
This results in printing n as 1, but in mysql client data aren't visible.
google says I must add conn.autocommit(True).
but I don't know why MySQLdb turns it off;
by default MySQLdb autocommit is false,
You can set autocommit to True in your MySQLdb connection like this,
conn=MySQLdb.connect(host="localhost",user="root",passwd="mysql",db="dang",charset="utf8")
conn.get_autocommit() #will return **False**
conn.autocommit(True)
conn.get_autocommit() #Should return **True** now
cursor = conn.cursor()
I don't know if there's a specific reason to use autocommit with GAE (assuming you are using it). Otherwise, you can just manually commit.
class postcon:
def POST(self):
conn=MySQLdb.connect(host="localhost",user="root",passwd="mysql",db="dang",charset="utf8")
cursor = conn.cursor()
n = cursor.execute("insert into d_message (mid,title,content,image) values(2,'xx','ccc','fff')")
conn.commit() # This right here
cursor.close()
conn.close()
if n:
raise web.seeother('/')
Note that you probably should check if the insert happened successfully, and if not, rollback the commit.
Connector/Python Connection Arguments
Turning on autocommit can be done directly when you connect to a database:
import mysql.connector as db
conn = db.connect(host="localhost", user="root", passwd="pass", db="dbname", autocommit=True)
or
import mysql.connector
db = mysql.connector.connect(option_files='my.conf', autocommit=True)
Or call conn.commit() before calling close.

Categories

Resources