i'm studying about mysql connection with python(pycharm)
i have question about curs.execute()
when it work and when it not work...
in my code i write remarks about not working point
import pymysql
try:
conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
conn.set_charset('utf8')
curs = conn.cursor(pymysql.cursors.DictCursor) #Dictionary cursor 생성
# curs = conn.cursor()
print("Connected to MySQL")
sql = "SELECT sno, midterm, final from db_score where midterm >= 20 and final >= 20 order by sno"
# sql = "select* from db_score"
curs.execute(sql)
#this point not work :(
except Exception as e:
print(str(e))
finally:
if conn:
curs.close()
conn.close()
print("MySql connection is closed")
and fetchall() didnt work :(\
import pandas as pd
import pymysql
xl_file = 'db_score.xlsx'
df = pd.read_excel(xl_file)
tp = list(df.itertuples(index=False, name=None))
# ('sno', 'attendance', 'homework', 'discussion', 'midterm', 'final', 'score', 'grade')
try:
conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
conn.set_charset('utf8')
#curs = conn.cursor(pymysql.cursors.DictCursor)
curs = conn.cursor()
print("Connected to MySQL")
sql = "INSERT INTO db_score VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
for i in range(0, len(df.index)):
# print('hi')
curs.execute(sql, tp[i])
#why work i dont know because other part is not working
# sql2 = "SELECT* from db_score"
# curs.execute(sql2)
# try execute, but not work
records = curs.fetchall()
for row in records:
print("why didn't work")
print(row)
#print not work :(
conn.commit()
except Exception as e:
print(str(e))
conn.rollback()
finally:
if conn:
curs.close()
conn.close()
print("MySql connection is closed")
please comment why work and why not work please...
thanks for watching
db connection is so hard:(
Related
I successfully access the database, however, I can't load the table inside the database. I am quite sure that the name of the table is correct, the database is a mimic iii database. Please give me a helping hand, thanks a lot!
import psycopg2
try:
connection = psycopg2.connect(user="postgres",
password="xxxxxxx",
host="localhost",
port="5432",
database="mimic")
cursor = connection.cursor()
postgreSQL_select_Query = "select * from admissions"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from mobile table using cursor.fetchall")
admissions_records = cursor.fetchall()
print("Print each row and it's columns values")
for row in admissions_records:
print("x = ", row[0], )
print("y = ", row[1])
print("z = ", row[2], "\n")
except (Exception, psycopg2.Error) as error:
print("Error while fetching data from PostgreSQL", error)
finally:
# closing database connection.
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
Here's the output:
Error while fetching data from PostgreSQL relation "admissions" does not exist
LINE 1: select * from admissions
^
PostgreSQL connection is closed
DELETE FROM ... doesn't work. The right parameters are passed to the function. No errors are returned.
I've tried to modify routing, passing parameters by POST and GET, and I've cried a lot in a fetal position.
conn = mysql.connect()
cursor = mysql.connect().cursor()
cursor.execute("SELECT * FROM food_on_the_table WHERE table_id = %s", table_id)
food_on_the_table = cursor.fetchall()
records = cursor.fetchall()
cursor.execute("DELETE FROM food_on_the_table WHERE row_id = %s", row_id)
conn.commit()
result = cursor.rowcount
message = "rows affected " + str(result)
cursor.close()
No row is deleted from the database. row_i is right, rows affected = 1 as expected.
Try this,
try:
conn = mysql.connect()
with conn.cursor() as cursor:
cursor.execute("SELECT * FROM food_on_the_table WHERE table_id = %s", table_id)
food_on_the_table = cursor.fetchall()
records = food_on_the_table
with conn.cursor() as cursor:
cursor.execute("DELETE FROM food_on_the_table WHERE row_id = %s", row_id)
conn.commit()
finally:
conn.close()
I'm new to python , I want to know how to do exception handling in python in a proper way.I want to raise an exception for failure of db connection.I also don't want to include all the lines of code in try block.I want to raise connection failure exception.How to do this?
try:
conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
, db="database")
mycursor = conn.cursor()
query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
val = (x,y,z)
mycursor.execute(query, val)
conn.commit()
conn.close()
print("Data inserted to db")
except Exception as ex:
print(ex)
conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
, db="database")
mycursor = conn.cursor()
query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
try:
mycursor.execute(query, val)
except MySQLdb.Error, e:
try:
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
return None
except IndexError:
print "MySQL Error: %s" % str(e)
return None
except TypeError, e:
print(e)
return None
except ValueError, e:
print(e)
return None
finally:
mycursor.close()
conn.close()
Something like:
connected = False
try:
conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
, db="database")
connected = True
except MySQLError as ex:
print(ex)
if connected:
mycursor = conn.cursor()
query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
val = (x,y,z)
mycursor.execute(query, val)
conn.commit()
conn.close()
print("Data inserted to db")
I have a piece of code which is taking Windows logs and inserting various pieces of information into an mySQL database. The code is running perfectly with no errors, but does not actually input the data into the table. The table remains blank. I pulled my mySQL syntax from an example with some modification, so I'm not entirely sure what is going wrong. I have a feeling it has either to do with the data types, or some changes I made to the syntax.
import sys
import pymysql
import pymysql.cursors
import win32evtlog # requires pywin32 pre-installed
import win32evtlogutil
import time
server = 'localhost' # name of the target computer to get event logs
logtype = 'System' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags =
win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
events = win32evtlog.ReadEventLog(hand, flags,0)
while True:
for event in events:
evt_tp = event.EventType
if evt_tp != (1 or 2 or 8):
eve_cat = str(('Event Category:', event.EventCategory))
eve_timegen = str(('Time Generated:', event.TimeGenerated))
eve_srcnm = str(('Source Name:', event.SourceName))
eve_id = str(('Event ID:', event.EventID))
eve_typ = str(('Event Type:', event.EventType))
data = event.StringInserts
if data:
print ('Event Data:')
for msg in data:
print(msg)
print(type(eve_cat))
print(type(eve_timegen))
print(type(eve_srcnm))
print(type(eve_id))
print(type(eve_typ))
print(type(data))
time.sleep(10)
else:
eve_cat = ('Event Category:', event.EventCategory)
eve_timegen = ('Time Generated:', event.TimeGenerated)
eve_srcnm = ('Source Name:', event.SourceName)
eve_id = ('Event ID:', event.EventID)
eve_typ = ('Event Type:', event.EventType)
data = event.StringInserts
print('There were no errors found')
print(eve_cat)
print(eve_timegen)
print(eve_srcnm)
print(eve_id)
print(eve_typ)
print(data)
time.sleep(10)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='ptest',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `win_logs` (`Category`, `TimeGenerated`, 'SourceName',
'EventID', 'Type') VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (eve_cat, eve_timegen, eve_srcnm, eve_id, eve_typ))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `Type` FROM `win_logs` WHERE `Category`=%s"
cursor.execute(sql, ('webmaster#python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
I can be very wrong.
But this is python.
Indentation matter.
Try just:
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `win_logs` (`Category`, `TimeGenerated`, 'SourceName`, 'EventID', 'Type') VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (eve_cat, eve_timegen, eve_srcnm, eve_id, eve_typ))
I guess your cursor is out of with scope
Eventually I would like to output the hosts to a list.
try:
cnx = mysql.connector.connect(user='root', password='passwd',
database='some_db')
cursor = cnx.cursor()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
retrieveQuery = ("SELECT host_name,product from server")
cursor.execute(retrieveQuery)
for host,prod in cursor:
print ("{},{}".format(host,prod))
Result looks good: [host1,PowerEdge]
retrieveQuery = ("SELECT host_name from server")
cursor.execute(retrieveQuery)
for host in cursor:
print ("{}".format(host))
Result: (u'host1',)
Why am I seeing (u',) with the same code but when just one column is selected ?
Any help is much appreciated
Your cursor row result is always tuple type, try:
for row in cursor:
print ("{}".format(row.host_name))
or
for host, in cursor:
print ("{}".format(host))