Python + Connecting to MySQL

I’m fairly experienced with PHP, specifically in conjunction with MySQL. That said, there’s little actual required knowledge of SQL to use MySQL. Any thing I need and don’t already know, I resort to W3CSchool.

With that said, I’m having a heck of a time getting Python to work appropriately on Windows 7. I’m actually not planning on making it work. Ever. I just spent 2 hours sifting various forums and the official Python website, and all I can find is that Windows 7 and Python have conspired to make it near impossible to open python files inside of the interpreter. Python works inside of Blender, and I’m leaving it at that.

My problem is that I can’t seem to find anything straightforward on the basic scripts for connecting to a MySQL server with Python. I saw a rather lengthy looking script here, but what I’m used to seeing in Python takes 3 lines and less than 50 characters, depending on values.

An example I might use in a real script is this:
session_start();
mysql_connect(“localhost”, “username”, “password”);
mysql_select_db(“username_database”);

I understand sessions to be something the browser uses, so I doubt Blender needs that. So the last two lines might be all I need.

Leaving me with my question. What is the script supposed to look like? I’m guessing there needs to be some command that allows access to the internet (port/socket, or some tech verbage). Any ideas where someone with no socket programming should start looking?

You don’t have to mess with sockets and data buffers directly. The library or API you are using takes care of all those details for you. Specifically:


mysql_connect("localhost", "username", "password");

Is code that would connect to the database. Usually this returns some kind of “Connection” object. You then use this Connection to the DB to make queries. Something like this pseudo-code:


Connection connection = mysql_connect(server, user, pass)
result = connection.exec(<SQL command>)

There is usually a significant amount of error handling that you have to do around calls like this. The “connect” call can fail for a variety of reasons:

  • SQL server is down
  • Wrong IP/port
  • Wrong user/pass
  • Target DB does not exist
  • etc

I would recommend looking at the documentation for the bindings that you are using. They should include some kind of “hello world” example that will show a fairly simple program that connects to the DB and runs a basic query.

This is a long time coming, but thanks. I actually skipped right to socket programming and plan to stick with that. Hopefully we can get our server running on flash memory (or… whatever) to avoid query times on the server (the server is currently written in PHP, and queries the database with MySQL functions).