473,569 Members | 2,782 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

can i set up a mysql db connection as a class ?

hey there,
i have a huge app that connects to MySQL. There are three threads that
are continually connecting and disconnecting to the db. The problem is,
if there is an error, it faults out sometimes without closing the
connection. i connect like this.
db = MySQLdb.connect (host="localhos t", user="MyUser",
passwd="MyPassw ord", db="Stuff")
cursor=db.curso r()

then i use the cursor.execute( "SELECT yadda yadda

my question is, is there a way i can set up a global connection so that
when the program loads, it connects once, then stays connected ? maybe
i could assign instances of the cursor ?

please someone let me know if you have any good ideas

sk

Apr 28 '06 #1
10 12361
that's definitely the way to go ..

-create a database_object
-initialise at start up
-then pass the database object to other classes as needed ...

If you want to get really fancy have a look at some ORM's ... I think
there is a Python one called SQLObject?

ne*****@xit.net wrote:
hey there,
i have a huge app that connects to MySQL. There are three threads that
are continually connecting and disconnecting to the db. The problem is,
if there is an error, it faults out sometimes without closing the
connection. i connect like this.
db = MySQLdb.connect (host="localhos t", user="MyUser",
passwd="MyPassw ord", db="Stuff")
cursor=db.curso r()

then i use the cursor.execute( "SELECT yadda yadda

my question is, is there a way i can set up a global connection so that
when the program loads, it connects once, then stays connected ? maybe
i could assign instances of the cursor ?

please someone let me know if you have any good ideas

sk

Apr 28 '06 #2
This is great !

ok, i dont really have a lot of time to get into the ORMS (before your
post, this is the first i have heard of it) and my stuff is due on
Monday. he he.

but, if i am able to make a global db connection, and multiple cursors
pointing to the same connection object, how do i pull that off without
making new db connections?

something like
class db(self):
def __init__(self):
db = MySQLdb.connect (host="localhos t", user="MyUser",
passwd="MyPassw ord",
db="Stuff")
def cursor(self):
cursor = db.cursor()
return cursor
then have in my threads that need to connect

cursor = db.cursor()
cursor2 = db.cursor()

and so on ? i may be way outta whack here. i am still new at classes,
methods, and modules.
i do have Essential Reference on the way from Amazon though ! :)

thanks again

Apr 28 '06 #3
your on the right track ... create something like this ( hope the formatting doesn't go to hay wire )

class DB_Connector(ob ject):

""" Humble Database Connection Class """

def __init__(self, host="localhost ", user="MyUser",p asswd="MyPasswo rd", **other_db_argu ments):

self.host = host
self.user = user
self.passwd = passwd

# Unpack Other Database Arguments Here
self.CreateConn ection()

def CreateConnectio n( self ):

self.cursor = MySQLdb.connect (self.host, self.user, self.passwd)

def DestroyConnecti on( self ):

self.cursor.clo se()

def Execute( self, sql_statement ):

self.cursor.Exe cute( sql_statement )

return self.cursor.Fet chAll()

Then when you run your program create an instance of the object

db_connection = DB_Connector( 'localhost', 'administrator' , 'betelgeuse99', auto_commit=1, other_keyword_a rg="yes" )

now when you pass the db_connection instance to other classes, a copy will be made automagically

thread_1_instan ce = ThreadingClass( db_connection )
thread_2_instan ce = ThreadingClass( db_connection )
thread_3_instan ce = ThreadingClass( db_connection )

should work ..

I hope this is useful

ne*****@xit.net wrote:
This is great !

ok, i dont really have a lot of time to get into the ORMS (before your
post, this is the first i have heard of it) and my stuff is due on
Monday. he he.

but, if i am able to make a global db connection, and multiple cursors
pointing to the same connection object, how do i pull that off without
making new db connections?

something like
class db(self):
def __init__(self):
db = MySQLdb.connect (host="localhos t", user="MyUser",
passwd="MyPassw ord",
db="Stuff")
def cursor(self):
cursor = db.cursor()
return cursor
then have in my threads that need to connect

cursor = db.cursor()
cursor2 = db.cursor()

and so on ? i may be way outta whack here. i am still new at classes,
methods, and modules.
i do have Essential Reference on the way from Amazon though ! :)

thanks again

Apr 28 '06 #4
Oops .. slight edit
now when you pass the db_connection instance to other classes, a reference will be passed automagically
Apr 28 '06 #5
On 04/28/2006 07:54 AM, *binarystar* wrote:

Just wondering: is there any risk of two threads accessing the Execute
function at the same time and getting something like this on the same
cursor object:

thread_1: self.cursor.Exe cute( sql_statement )
thread_2: self.cursor.Exe cute( sql_statement )
thread_1: return self.cursor.Fet chAll()
thread_2: return self.cursor.Fet chAll()

In that case the queries would seriously be messed up. My intuition says
this would need some locking or a 'cursor-pool'.

best wishes,

Winfried

your on the right track ... create something like this ( hope the
formatting doesn't go to hay wire )

class DB_Connector(ob ject):

""" Humble Database Connection Class """
def __init__(self, host="localhost ",
user="MyUser",p asswd="MyPasswo rd", **other_db_argu ments):
self.host = host
self.user = user
self.passwd = passwd
# Unpack Other Database Arguments Here
self.CreateConn ection()
def CreateConnectio n( self ):
self.cursor = MySQLdb.connect (self.host, self.user,
self.passwd)
def DestroyConnecti on( self ):
self.cursor.clo se()
def Execute( self, sql_statement ):
self.cursor.Exe cute( sql_statement )
return self.cursor.Fet chAll()
Then when you run your program create an instance of the object

db_connection = DB_Connector( 'localhost', 'administrator' ,
'betelgeuse99', auto_commit=1, other_keyword_a rg="yes" )

now when you pass the db_connection instance to other classes, a copy
will be made automagically

thread_1_instan ce = ThreadingClass( db_connection )
thread_2_instan ce = ThreadingClass( db_connection )
thread_3_instan ce = ThreadingClass( db_connection )

should work ..
I hope this is useful

Apr 28 '06 #6
I suppose that is possible because you are calling the one instance of a cursor object ... maybe you have to create a copy of the cursor object, rather than passing a reference to the one object? or set up the db_connection objects inside each of the threads? ..
Winfried Tilanus wrote:
On 04/28/2006 07:54 AM, *binarystar* wrote:

Just wondering: is there any risk of two threads accessing the Execute
function at the same time and getting something like this on the same
cursor object:

thread_1: self.cursor.Exe cute( sql_statement )
thread_2: self.cursor.Exe cute( sql_statement )
thread_1: return self.cursor.Fet chAll()
thread_2: return self.cursor.Fet chAll()

In that case the queries would seriously be messed up. My intuition says
this would need some locking or a 'cursor-pool'.

best wishes,

Winfried

your on the right track ... create something like this ( hope the
formatting doesn't go to hay wire )

class DB_Connector(ob ject):

""" Humble Database Connection Class """
def __init__(self, host="localhost ",
user="MyUser",p asswd="MyPasswo rd", **other_db_argu ments):
self.host = host
self.user = user
self.passwd = passwd
# Unpack Other Database Arguments Here
self.CreateConn ection()
def CreateConnectio n( self ):
self.cursor = MySQLdb.connect (self.host, self.user,
self.passwd)
def DestroyConnecti on( self ):
self.cursor.clo se()
def Execute( self, sql_statement ):
self.cursor.Exe cute( sql_statement )
return self.cursor.Fet chAll()
Then when you run your program create an instance of the object

db_connection = DB_Connector( 'localhost', 'administrator' ,
'betelgeuse99', auto_commit=1, other_keyword_a rg="yes" )

now when you pass the db_connection instance to other classes, a copy
will be made automagically

thread_1_instan ce = ThreadingClass( db_connection )
thread_2_instan ce = ThreadingClass( db_connection )
thread_3_instan ce = ThreadingClass( db_connection )

should work ..
I hope this is useful

Apr 28 '06 #7
On 04/28/2006 08:35 AM, *binarystar* wrote:

Looking better at the """ Humble Database Connection Class """: if I am
not mistaken, it seems to mix up connections and cursors.

MySQLdb has a thread safety level of '1', meaning: "Threads may share
the module, but not connections". So you have to give each thread an own
connection. Beside of that I would prefer not to share the cursor
object, although it should not really matter.

The following should work and make the cursors private to the Execute
function (untested):

class DB_Connector(ob ject):

""" Humble Database Connection Class """
def __init__(self, host="localhost ",
user="MyUser",
passwd="MyPassw ord",
**other_db_argu ments):
self.host = host
self.user = user
self.passwd = passwd
# Unpack Other Database Arguments Here
self.CreateConn ection()

def CreateConnectio n(self):
self.connection = MySQLdb.connect (self.host,
self.user,
self.passwd)

def DestroyConnecti on(self):
self.connection .close()

def Execute(self, sql_statement):
cursor = self.connection .cursor()
cursor.execute( sql_statement)
result = cursor.fetchall ()
cursor.close()
return result

I suppose that is possible because you are calling the one instance of a
cursor object ... maybe you have to create a copy of the cursor object,
rather than passing a reference to the one object? or set up the
db_connection objects inside each of the threads? ..

Winfried Tilanus wrote:
On 04/28/2006 07:54 AM, *binarystar* wrote:

Just wondering: is there any risk of two threads accessing the Execute
function at the same time and getting something like this on the same
cursor object:

thread_1: self.cursor.Exe cute( sql_statement )
thread_2: self.cursor.Exe cute( sql_statement )
thread_1: return self.cursor.Fet chAll()
thread_2: return self.cursor.Fet chAll()

In that case the queries would seriously be messed up. My intuition says
this would need some locking or a 'cursor-pool'.

best wishes,

Winfried

your on the right track ... create something like this ( hope the
formatting doesn't go to hay wire )

class DB_Connector(ob ject):

""" Humble Database Connection Class """
def __init__(self, host="localhost ",
user="MyUser",p asswd="MyPasswo rd", **other_db_argu ments):
self.host = host
self.user = user
self.passwd = passwd
# Unpack Other Database Arguments Here
self.CreateConn ection()
def CreateConnectio n( self ):
self.cursor = MySQLdb.connect (self.host, self.user,
self.passwd)
def DestroyConnecti on( self ):
self.cursor.clo se()
def Execute( self, sql_statement ):
self.cursor.Exe cute( sql_statement )
return self.cursor.Fet chAll()
Then when you run your program create an instance of the object

db_connection = DB_Connector( 'localhost', 'administrator' ,
'betelgeuse99', auto_commit=1, other_keyword_a rg="yes" )

now when you pass the db_connection instance to other classes, a copy
will be made automagically

thread_1_instan ce = ThreadingClass( db_connection )
thread_2_instan ce = ThreadingClass( db_connection )
thread_3_instan ce = ThreadingClass( db_connection )

should work ..
I hope this is useful

Apr 28 '06 #8
So this opens and closes the connection every time i run the query?
thats cool. i think that would fit in well. so when i need to run the
query, i pass something like

query = "SELECT * FROM `Table` WHERE `foo` = 'bar'"

result = DB_Connector.Ex ecute(query)

and the result would be the same as if i ran the query right there in
the thread?

thanks for all your help gents, this is helping me a lot.

Apr 28 '06 #9
way cool, i think that this will work.

thanks very much

-sk

Apr 28 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
6454
by: Tom Martin | last post by:
I'm a Java Web developer NEWBIE that has inherited a website that fails every 2 hours due to poor connection pooling between Tomcat 4.0.6 and mySQL. In efforts to resolve this problem, I've created another replica DEVELOPMENT website and upgraded it to Tomcat 4.1.27. I was told this version of Tomcat supports Database Connection Pooling...
0
2551
by: sridhar nagabhurshana | last post by:
hello I am trying to connect to mysql database using connector/J jdbc driver this is my code import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
0
4235
by: Robert Mazur | last post by:
MySQL 5.0 alpha (binary install) on Solaris 9 -or- RedHat 8.0 mysql-connector-java-3.0.8-stable ----------------------- Is there something different going on with JDBC and the alpha version of MySQL 5.0? When trying to connect I am getting: ** BEGIN NESTED EXCEPTION **
0
3931
by: Mike Chirico | last post by:
Interesting Things to Know about MySQL Mike Chirico (mchirico@users.sourceforge.net) Copyright (GPU Free Documentation License) 2004 Last Updated: Mon Jun 7 10:37:28 EDT 2004 The latest version of this document can be found at: http://prdownloads.sourceforge.net/souptonuts/README_mysql.txt?download
0
637
by: Peter Höltschi | last post by:
I try to install MySQL Connection/J on a Windows XP box. MySQL on localhost works fine. But I cannot load the MySQL Connection/J Driver. The CLASSPATH variable is set like this: CLASSPATH=c:\j2sdk1.4.2_04\jre\lib\ext\mysql-connector-java-3.0.14-production-bin.jar To test it I use this simple code (just to test if the Driver is loaded):...
7
2486
by: Ike | last post by:
Let's say I have a MySQL 4.12 database, opened to the internet on 111.111.111.111 allowing all incoming and outgoing ports. I have a username and password setup, which CAN connect to this database, from 222.222.222.222. Also on 222.222.222.222, which is running Tomcat, I have a Java servlet, called, say, servlet.class in WEB-INF/classes....
8
4629
by: menmysql | last post by:
i am not bale to solve this problem since two weeks i am trying to access records from mysql database using jsp. inside this jsp program i wrote all my JDBC code. it is working very nicely and displaying records. now i wrote all the JDBC code in .java and i am accessing that code in jsp file. but this time i am getting only exceptions not...
5
2025
oll3i
by: oll3i | last post by:
my librarybean package library.ejb; import java.sql.*; import javax.ejb.*; import library.common.*; @Stateless @Remote
1
2515
by: paulq182 | last post by:
PLEASE HELP ME WITH MY CODE?? import java.sql.*; import java.io.*; class min_filmdb_rel_mysql { public static void main (String args ) throws SQLException, IOException {
0
7693
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7917
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7665
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6277
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5501
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
1
2105
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1207
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.