Python operations on the MySQL database, pythonmysql Database
In Python, you can use the MySQLdb module to connect to the MySQL database and perform operations on the MySQL database.
【Step 1]Install MySQL
Reference: http://blog.csdn.net/Jerry_1126/article/details/20837397
【Step 2]ConnectMySQL
Welcome to the MySQL monitor. commands end with; or \ g. your MySQL connection id is 5 Server version: 5.5.19 MySQL Community Server (GPL) mysql> # create database mysql> create database python; Query OK, 1 row affected (0.09 sec) # use Database mysql> use python; Database changed # create table mysql> create table people (name VARCHAR (30), age INT, sex CHAR (1); Query OK, 0 rows affected (0.44 sec) # insert data mysql> insert into people values ('Tom ', 20, 'M'); Query OK, 1 row affected (0.13 sec) mysql> insert into people values ('jack', NULL, NULL); Query OK, 1 row affected (0.06 sec) # View data mysql> select * from people; + ------ + | name | age | sex | + ------ + | Tom | 20 | M | Jack | NULL | + ------ + ------ + 2 rows in set (0.05 sec)
Http://sourceforge.net/projects/mysql-python
Download the exe file that matches your operating system and Python version, and click Next to complete the installation. The installation is successful!
>>> import MySQLdb>>>
Import MySQLdb # import MySQLdb module db = MySQLdb. connect (host = 'localhost', # connect to the database, the server is the local user = 'root', # the user name is: root passwd = '000000', # The password is: 1234 db = 'python') # Database: pythoncur = db. cursor () # obtain the database cursor cur.exe cute ('insert into people values ("Jee", 21, "F") ') # Execute SQL, add record res = cur.exe cute ('delete from people where age = 20') # Run the SQL statement to delete the record db. commit () # submit the transaction res = cur.exe cute ('select * from people') # execute the SQL statement to obtain the record res = cur. fetchall () # obtain all data print (res) # print data cur. close () # close the cursor db. close () # close the database connection
For API definitions, see:
Http://blog.csdn.net/jerry_1126/article/details/40037899