Python link Database

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.