What is Python’s equivalent of Perl’s DBI and how do I use it? More specifically, what is the Python equivalent of the following Perl code?
use DBI;
# connect to a MySQL database
my $dbh = DBI->connect("dbi:mysql:database=$database; host=localhost; port=3306", $user, $pass);
# select and read a few rows
my $sth = $dbh->prepare("SELECT id, name FROM table WHERE id <= ?;");
$sth->execute(321);
while (my @row = $sth->fetchrow_array) {
my $id = $row[0];
my $name = $row[1];
print "$id. $name\n";
}
# write to the database
$sth = $dbh->prepare("INSERT INTO table (id, name) VALUES (?, ?);");
$sth->execute(123, "foo");
Python database API use a common convention, that is pretty much the same across different databases (but not quite!). You can read the MySQLdb documentation here.
There is also a more feature-rich interface to mysql, called oursql. It has real parametrization (not just glorified string interpolation), server-side cursors, data streaming and so on.