How to Connect a Database to Python Updated on February 15, 2022 by InMotion Hosting Contributor 2 Minutes, 2 Seconds to Read It is helpful to understand how to connect a database to Python scripts for serving dynamically generated web pages and collaborative reports. Python is almost always included in Linux distributions and used for multiple applications already. You don’t need PHP for this. Below we’ll cover how to create a Python database connection (MySQL/MariaDB) in the Linux terminal. How to Connect a Database to Python 2.7 Log into SSH.From your website root directory, create a Python script file in the “cgi-bin” directory: touch cgi-bin/test-db.pyChange the file’s permissions to 755:chmod 755 cgi-bin/test-db.pyIf you wish to execute Python scripts in web browsers, edit your Apache .htaccess file:nano .htaccessAdd the following at the top of the file and save changes: AddHandler cgi-script .pyTo complete the Python database connection you’ll need to know the database host (“localhost” if on the same system), name, username, and user password.Run Python:pythonEnsure you have the MySQL Python module installed:import MySQLdb If you receive no notification, that means it is installed. You’ll need to install the module if you receive the error “ImportError: No module named mysqldb.”Exit Python:exit ()If you need to install it, we recommend using your OS repositories. You can also use PIP.Alma / Enterprise Linux: sudo yum install MySQL-pythonUbuntu:sudo apt-get install python-pip python-dev libmysqlclient-devPIP:pip install MySQL-pythonEdit your Python script:nano cgi-bin/test-db.pyInsert the code below to connect to the database and run “SELECT VERSION(),” which shows our current version of MySQL. Replace the database user, password, and database.#!/usr/bin/env pythonimport MySQLdb# connect to the databasedb = MySQLdb.connect("localhost","user","password","database" )# setup a cursor object using cursor() methodcursor = db.cursor()# run an sql questioncursor.execute("SELECT VERSION()")# grab one resultdata = cursor.fetchone()# begin printing data to the screenprint "Content-Type: text/html"printprint """<!DOCTYPE html><html><head><title>Python - Hello World</title></head><body>"""print "Database version : %s " % dataprint"""</body></html>"""# close the mysql database connectiondb.close()Save changes.Run the Python script:python test-db.py The results should show basic HTML markup and your current database version. You can also visit the Python script URL in the web browser if you updated your web server configuration file. You’ll see the database version line. Congrats on learning how to connect a database to Python 2.7+. Learn more about programming with Python. If you don’t need cPanel, don't pay for it. Only pay for what you need with our scalable Cloud VPS Hosting. CentOS, Debian, or Ubuntu No Bloatware SSH and Root Access Share this Article InMotion Hosting Contributor Content Writer InMotion Hosting contributors are highly knowledgeable individuals who create relevant content on new trends and troubleshooting techniques to help you achieve your online goals! More Articles by InMotion Hosting Related Articles How To Create a PHP Redirect (301, 302, and Dynamic Redirect Examples) Connect to SFTP for Shared Hosting Accounts Using FileZilla FTP Basics for Dedicated Servers How to Install Jekyll and Launch a New Site How to Host AI-Prompt Generated Websites on Shared Hosting What is your default PHP.ini file? Getting Started Guide: FTP Configuring your site in WS_FTP Schedule Social Media Posts With Buffer FTP Error – 421 Too Many Connections
I was looking for information on how to install Flask and it instead provided an article that didn’t even mention Flask. Please add a section describing how to install Flask for web development.
Hello Tmhudg, If were only going to be affecting your, it may be possible to run it. But it appears to be more of a server-wide thing, which, since you’re on a shared server account-type, is not going to be allowed. If you want to inquire with live support, you can email [email protected] and you’ll get a response through email. If you have any further questions, please contact technical support or leave a comment at the bottom of the page. Regards, Arnel C.
Is it possible to get something like bottle installed? I’m looking at bottle as my server engine and would really like to get it working here. https://bottlepy.org/docs/dev/tutorial_app.html#server-setup Thanks
Hello noble, I just responded to your original question with a resolution to your issue. Please check that to see if it will help you. It seems that some select older servers do not have that module installed. As they are older servers and will likely soon be decommissioned, adding and updating them on the server wide level is not something the Systems team will do. We can, however, move anyone who encounters this issue to newer servers that do have the capability. The newest servers also run an updated version of Python (2.6) and do have the MySQLdb module installed. I do apologize for any misinformation you may have gotten with your support ticket. I will take measures to ensure a request of this nature is handled correctly in the future. Best Regards, Scott M
Warning for other users on shared hosting (business) servers, as of 9/20/2012 this example appears to be broken due to MySQLdb library not being properly installed for the current version of python in /usr/lib/python2.4/site-packages on shared hosting servers. Since you won’t have SSH access as a business customer (you need to buy VPS or dedicated hosting for ssh access), you will not be able to install the setuptools-0.6c11 and MySQL-python-1.2.3 on your own. And the inMotion support folks said they are unwilling to add MySQLdb to the latest python version library directory on their shared servers. I would encourage you to ask inMotion tech support to fix the python MySQLdb installation on your shared server. Maybe if enough customers ask for this they will eventually agree to do it. The work-around that inMotion tech support suggested is to have my python CGI script call another external script (presumably written in PHP or Perl or some other scripting language that is able to access MySQL properly), and have the child script read/write data from/to my database on behalf of the python script. Very messy in my opinion. I guess I will just stick with PHP or Perl for CGI for now whenever I need to access MySQL database since python is incapable of doing so on our server.