Connect to MySQL with python

The mysql libraries are not per see installed with python, thus:

sudo apt-get install python-mysql

Script:


#!/usr/bin/python
import MySQLdb

db = MySQLdb.connect(host="localhost", # your host, usually localhost
    user="tomas", # your username
    passwd="tomas1234", # your password
    db="test") # name of the data base

# Create a cursor object that executes all required queries
cur = db.cursor()

# create sample table
cur.execute("CREATE TABLE IF NOT EXISTS tomastest(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, data VARCHAR(100))")

# create sample data
cur.execute("INSERT INTO tomastest(data) VALUES('Test data'); commit;")

# execute select sql
cur.execute("SELECT * FROM tomastest")

# Get the number of rows in the resultset
numrows = cur.rowcount
print "Rows count: ",numrows
for row in cur.fetchall():
    print row[0], row[1]
db.close()

If not providede, thus create test mysql db (sMySQL Docs)

mysql> CREATE DATABASE test;
mysql> use test

If not already exist create user (MySQL Docs)

mysql> CREATE USER 'tomas'@'localhost' IDENTIFIED BY 'tomas1234';
mysql> GRANT ALL ON test.* TO 'tomas'@'localhost';

Schreibe einen Kommentar