D
D
des1roer2016-05-30 19:25:21
Python
des1roer, 2016-05-30 19:25:21

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2016-05-30
@NeiroNx

And who will return the value? Uncle Vasya?

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()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question