4

Hi i have problem regarding db connection. i want to put db connection in seprate file and can use in multiple files.

i have tried this

connection.py

import pymysql
import mysql.connector

class Connection:

    def __init__(self):
        conn = mysql.connector.connect(host="localhost", user="root", password="", db="")
        cur = conn.cursor()
        return cur, conn


main.py

import connection

cur, conn = connection.Connection()

Error

cur, conn = connection.Connection()
TypeError: __init__() should return None, not 'tuple'
3
  • You want a function, not a class…!? Commented Mar 4, 2021 at 10:30
  • 2
    The error message is explicit: the special __init__ method is expected to return None (or not use return at all which is equivalent) Commented Mar 4, 2021 at 10:31
  • I'd suggest you use a config file instead, but otherwise just use a simple function like deceze suggested and you're fine. Commented Mar 4, 2021 at 10:35

1 Answer 1

7

connection.py

import pymysql
import mysql.connector

def get_connection():
    conn = mysql.connector.connect(host="localhost", user="root", password="", db="")
    cur = conn.cursor()
    return cur, conn

main.py

import connection

cur, conn = connection.get_connection()

Sign up to request clarification or add additional context in comments.

4 Comments

Great, and then, how to close the connection in a function in the connection.py?
@herhor67 You can close the connection by conn.close() However, it is not appropriate because if you close the connection in get_connection function, you can't use it.
That was my point. It would be great to have an init and deinit functions, but when done in this way, you need to pass the conn variable to the deinit... God I hate Python.
@herhor67 I got it. You can make it to class and override __init__ and __del__ function. I might think pymysql already got this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.