Function: Working with MySQL database via Python
1. Installing Mysql-python
To enable Python to operate MySQL requires the Mysql-python driver, which is a necessary module for Python to operate MySQL.
: https://pypi.python.org/pypi/MySQL-python/
You can install it after you download it.
Detect whether the installation through Import MySQLdb view, how did not install successfully, will be error.
The installation was successful and the import was not prompted.
2.basic operation of MYSQ
Review the basic MySQL operation
0. See MySQL information status;1the entire command is incorrectly written and can be entered in \c to cancel execution.2. Single-line command write errors you can press the ESC key to clear a row3. Create a separate administrator and password for a database grant all on houdunwang.* to"HDW"@"localhost"Identified by"HDW";4. Create database cerate databases Houdunwang; Create DATABASE HD default character set UTF8;//specifying a character set5. Delete database drop databases Houdunwang;6. CREATE TABLE students (ID int () PRIMARY key auto_increment,name varchar (2), age tinyint)); CREATE table user (id int (Unsigned primary key auto_increment,name varchar, age tinyint (2) ) default character set UTF8;//specifying a character set7. View all datasheets show tables;8. View the specified data table desc students;9. Add insert into students (Name,age) VALUES ("Zhansan", 22);10. Export the database (exit the database first) C:\users\admin>mysqldump-uroot-p houdunwang>d:/Houdunwang.sql11. Delete data table drop table students;12. Import Database C:\users\admin>mysql-uroot-p Houdunwang < d:/Houdunwang.sql13. Execute the external SQL statement (select a database first) source D:/houdunwang.sql;
3. Working with Python
writing data in the database
ImportMysqldbconn= MySQLdb.connect ("localhost","Root","Root","HD") #连接数据库cur=conn.cursor () #创建游标cur. Execute ("CREATE TABLE student (ID int, name varchar, class varchar (), age varchar )") Cur.execute ("INSERT into student values (' 2 ', ' Tom ', ' 3 Year 2 class ', ' 9 ')") Cur.close () Conn.commit () Conn.close ( )
traversing data in a database
ImportMysqldbconn= MySQLdb.connect ("localhost","Root","Root","HD") cur=conn.cursor ()#cur.execute ("CREATE TABLE student (ID int, name varchar (), class varchar (), age varchar ())")#Cur.execute ("INSERT into student values (' 2 ', ' Tom ', ' 3 Year 2 class ', ' 9 ')")Res=cur.execute ("SELECT * FROM Student")PrintResinfo=Cur.fetchmany (RES) forIinchInfo:Printicur.close () conn.commit () Conn.close ( )
Python operation MySQL