Various database operation modules and connection instances commonly used in python

  • 2020-04-02 13:41:43
  • OfStack

At work, it is often useful to use python to access various database requirements, such as reading point configuration files from oracle or writing result information to mysql.
Here's a list of the various modules you might use.

Sqlite3: built-in modules
With sqlite, which is sometimes really convenient, I think it does the claimed "zero configuration." Support for sqlite3 has been built into python since version 2.5, and it's easy to use. Follow the documentation:


# Open the db File to get the connection 
conn = sqlite3.connect(' Data file name ')
# To obtain the cursor 
c = conn.cursor()
# perform SQL
c.execute('''SQL  fragment ''')
# If there are modifications to the data, then yes commit the 
conn.commit()
# Close the cursor 
c.close()
# Close the connection 
conn.close()

In addition, you can refer to previous articles on the use of sqlite under C and bash.

The oracle: cx_Oracle

In fact, apart from the fact that sqlite3 is really a small database, there's another reason why other databases operate in python in much the same way as sqlite3, which means that python has pretty much unified the interface to the database.
Open the cx_Oracle documentation page, and you'll see that the style is also similar to python documentation, because they're all made with Sphinx. The way the module is used is more similar. Instead of the line that gets the connection in the above code, replace it with this:


conn = cx_Oracle.connect('username/password@TNSname')

That's it. As long as the user name, password, TNS constitute a string, pass in, you can get an oracle connection.

Mysql: MySQLdb

Very similar to the previous two, use one of the following two syntaxes when joining:


conn = MySQLdb.connect('host', 'username', 'password', 'database')
conn = MySQLdb.connect(host="host", user="username", passwd="password", db="database")

Next, just use it as sqlite as well.

Excel: pyExcelerator

Well, I'll admit that excel isn't a database, it's just written here to top up, haha. Because once in a while you still have to take data from excel that someone else has sent you.
It's easy to read files using pyExcelerator:

sheets=pyExcelerator.parse_xls('xxx.xls')

After this, sheets is the entire workbook, which is a list of worksheets, and a worksheet corresponds to a tuple in the format of: (' worksheet name ', content), which is a dict, key is a tuple (rows, columns), and value is the content of the corresponding cell. It does look a little convoluted, but there aren't many applications for excel, so let's just go with that.
In addition, pyExcelerator also supports writing data to excel. If you need to save query results to excel, you can try it out.


Related articles: