Mysql + python?

main.py
import mysql.connector
from mysql.connector import Error
from mysql.connector import MySQLConnection, Error
from mysql_config import connect

def insert_books(books):
 query = "INSERT INTO operator(session_id,operator_login)" \
"VALUES(%s,%s)"


try:
 conn = connect
 cursor = conn.cursor()
 cursor.executemany(query, books)

conn.commit()
 except Error as e:
 print('Error:', e)

finally:
cursor.close()
conn.close()


def main():
 books = [('Harry Potter And The Order Of The Phoenix', '9780439358071'),
 ('Gone with the Wind', '9780446675536'),
 ('Pride and Prejudice (Modern Library Classics)', '9780679783268')]
insert_books(books)


if __name__ == '__main__':
 main()


mysql_config

import mysql.connector
from mysql.connector import Error

def connect():
 """ Connect to MySQL database """
try:
 conn = mysql.connector.connect(host='localhost',
database='mydb',
user='root'
password=")
 if conn.is_connected():
 print('connection established.')
else:
 print('connection failed.')

 except Error as e:
print(e)

finally:
conn.close()

if __name__ == '__main__':
 connect()


get

C:\Python27\python.exe F:/python/main.py
Traceback (most recent call last):
File "F:/python/main.py", line 33, in
main()
File "F:/python/main.py", line 29, in main
insert_books(books)
File "F:/python/main.py", line 10, in insert_books
cursor = conn.cursor()
AttributeError: 'function' object has no attribute 'cursor'

Process finished with exit code 1
July 9th 19 at 10:28
1 answer
July 9th 19 at 10:30
And the value who will return? Uncle Bob?
def connect():
 """ Connect to MySQL database """
try:
 conn = mysql.connector.connect(host='localhost',
database='mydb',
user='root'
password=")
 if conn.is_connected():
 print('connection established.')
else:
 print('connection failed.')
 return conn
 except Error as e:
print(e)

finally:
 conn.close()
not often you can complain about Python. what have I forgotten? - domenic.Jast commented on July 9th 19 at 10:33
Function def connect (): should , as a result of success or failure to return the class conn connector. - Iliana_Strosi commented on July 9th 19 at 10:36
and secondly conn = connect() - Iliana_Strosi commented on July 9th 19 at 10:39
C:\Python27\python.exe F:/python/main.py
Traceback (most recent call last):
connection established.
('Error:', OperationalError(-1, 'MySQL Connection not available.', None))
File "F:/python/main.py", line 32, in
main()
File "F:/python/main.py", line 28, in main
insert_books(books)
File "F:/python/main.py", line 20, in insert_books
cursor.close()
UnboundLocalError: local variable 'cursor' referenced before assignment - domenic.Jast commented on July 9th 19 at 10:42
Did konekt immediately after receiving not closed in the finally? - sherwood_Daugherty commented on July 9th 19 at 10:45
: closed - marilyne_Roh commented on July 9th 19 at 10:48

Find more questions by tags Python