Python mysql - cursor.close() db.close() -
i opening, accessing, writing, etc, database within various classes , threads in application. have 1 database self.run_params["db"]
using access throughout application.
question 1: should closing cursor each time after each individual access?
question 2: application runs , accesses database @ various different points, should close database after each access, or close database on exit of application?
import mysqldb import warnings warnings.filterwarnings('ignore') self.run_params = {} self.run_params["databasename"] = "transporterdatabase" self.run_params["tablename"] = "transportertable" ## create databse if not exist ## db = mysqldb.connect(host="localhost", user="root", passwd="password") cur = db.cursor() cur.execute("create database if not exists " + self.run_params["databasename"]) db.close() ## create table if not exist ## self.run_params["db"] = mysqldb.connect(host="localhost", user="root", passwd="password", db=self.run_params["databasename"]) cur = self.run_params["db"].cursor() cur.execute("create table if not exists " + self.run_params["tablename"] + "(jobid int not null auto_increment, primary key(jobid), location varchar(5000), mode varchar(50), process varchar(10), status varchar(30), title varchar(500), vendorid varchar(100), provider varchar(100), packagetype varchar(50), assetupdate varchar(5), foldersubmission varchar(5), submittime varchar(50), priority varchar(5));") cur.close() ###################### ## use database info ## cur = self.params["db"].cursor() cur.execute("select * %s order %s" % (self.params["tablename"], 'priority')) row in cur.fetchall() : jobid = row[0] indir1 = row[1] runningmode = row[2] process = row[3] status = row[4] title = row[5] vendorid = row[6] provider = row[7] packagetype = row[8] assetupdate = row[9] foldersubmission = row[10] cur.close()
you can create single database object accessing database , use locking mechanism (such semaphore or rlock) synchronized access object.
Comments
Post a Comment