1. First to download the installation database
2. Install the MySQL module (pip install Mysql;easy_install MySQL)
3. Link Database
#-*-coding:utf-8-*-
Import MySQLdb
Import Sys
Reload (SYS)
Sys.setdefaultencoding (' UTF8 ')
Conn=mysqldb.connect (host= "127.0.0.1",
port=3306,
User= "Root",
Passwd= "123456", #密码
db= "Test",
charset= "UTF8",)
Cur=conn.cursor () creates a cursor by obtaining the cursor () method under the database connection conn.
Cur.execute () can write pure SQL statements by using the cursor cur operation execute () method
Cur.close () Close cursor
The Conn.commit () method commits the thing and must have this method when inserting a piece of data into the database, otherwise the data is not actually inserted
4. Create a table
#创建数据表 #cur.execute ("CREATE TABLE student (ID int, name varchar (), class varchar (), age varchar ())") #插入一条数据, Note the type of data Utf8#cur.execute ("INSERT into student values (' 2 ', ' Tom ', ' 3 Year 2 class ', ' 9 ')") #修改查询条件的数据 #cur.execute ("Update Student set class= ' 3 Year 1 class ' WHERE name = ' Tom ' ") #删除查询条件的数据 the #cur.execute (" Delete from student where age= ' 9 ' ") #查询数据语句
5: Insert Data
Normal create
Cur.execute ("insert into Student values (' 2 ', ' Tom ', ' 3 year 2 class ', ' 9 ') ")
ID self-increment, create TABLE
Cur.execute (" insert Into student (name,class,year) values (' Tom ' , ' 3 Year 2 class ', ' 9 ') ")
can be replaced
sql= insert into student (name,class,year) values ('%s ',, ' %s ', '%s ') #书写格式, parentheses cannot be dropped
Cur.execute ( ' Tom ') , ' 3 Year 2 class ', ' 9 ' )
6. Get multiple data in a table
#获得表中有多少条数据aa =cur.execute ("SELECT * from student") print aa# how much data in the printed table info = cur.fetchmany (aa) for II in info: Print II
7. Database Operations on tables
drop table <table name> Delete Table
Python link Database