Hi
I wanted to know how can I make sure that table exist in my database.

class Record:
    def __init__(self):
        self.conn = MySQLdb.connect( host = 'localhost', user = 'root', passwd = 'abcd', db = 'justfun')
        self.cursor = self.conn.cursor()
        self.cursor.execute("DROP TABLE IF EXISTS book")
        self.cursor.execute( """CREATE TABLE book (name char(40), lastname char(40), petname char (40)) """)

main()
Rec = Record()

The problem here is how can i check if my table exist or not.
I dont want to create a table if its already exists.

Thanks .

The standard way is

if not os.path.isfile(full_file_name):
   CREATE Table

Hi
I wanted to know how can I make sure that table exist in my database.

class Record:
    def __init__(self):
        self.conn = MySQLdb.connect( host = 'localhost', user = 'root', passwd = 'abcd', db = 'justfun')
        self.cursor = self.conn.cursor()
        self.cursor.execute("DROP TABLE IF EXISTS book")
        self.cursor.execute( """CREATE TABLE book (name char(40), lastname char(40), petname char (40)) """)

main()
Rec = Record()

The problem here is how can i check if my table exist or not.
I dont want to create a table if its already exists.

Thanks .

hi,

Do you want to drop and create table every time you instatiate your above class? If so, you can keep drop statement within try ... finally block. By doing so, if the table does not exists then you get exception saying UNKNOWN TABLE NAME(means, table does not present). And the code within finally is what you always expect that is create table.

class Record:
    def __init__(self):
        try:
            self.conn = MySQLdb.connect( host = 'localhost', user = 'root', passwd = 'abcd', db = 'justfun')
            self.cursor = self.conn.cursor()
            self.cursor.execute("DROP TABLE IF EXISTS book")

        # try catching connection refuse and other exceptions. Sorry i dont remember exception to catch
        #except :
            #...

        # code within finally block will execute irrespective of exception
        finally:
            self.cursor.execute( """CREATE TABLE book (name char(40), lastname char(40), petname char (40)) """)
            
main()
Rec = Record()

OR

If you want to create table only if it is not already present in the database, then you can do so with query statement itself.

# To create a table by checking if the table already exists in MySQL. CREATE TABLE IF NOT EXISTS book (name char(40), lastname char(40), petname char (40)) It is good practice to place your code within try...except block, which helps you catching exact problems. Sorry for the incomplete code. I hope this helps to some extent.

kath.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.