pythonでのpostgresのDB処理で、最初にcursorを作成して、
必要な時に別クラス(別ファイル)からcursorを使用したいと考えています。
現状は以下のようにDbaccessクラスのglobal変数に設定しています。
grobal変数はあまり使用したくないのですが、
使用しないでできる方法教えていただけませんでしょうか
main.py
class test_g():
test = Dbaccess():
test.db_init()
test2 = Select1()
test2.db_select()
test3 = Select2()
test3.db_select()
Dbaccess.py
import psycopg2
class Dbaccess():
cur = ""
def db_init():
global cur
conn = psycopg2.connect("dbname=test user=postgres")
cur = conn.cursor()
def get_cur():
global cur
return cur
select1.py
import psycopg2
import Dbaccess
class Select1():
def db_select():
cur_sel = Dbaccess.get_cur()
sql = "select * from table_a"
cur_sel.execute(sql)
Select2.py
import psycopg2
import Dbaccess
class Select2():
def db_select():
cur_sel = Dbaccess.get_cur()
sql = "select * from table_b"
cur_sel.execute(sql)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/02/13 08:51