Novice Learning Python (ix) operation database MySQL

Source: Internet
Author: User

Import Pymysql     #导入pymysql模块

coon=pymysql.connect ( #连接数据库
Host= ' 192.168.13.4 ', user= ' abc ', passwd= ' 123456 ', #host为数据库的ip
port=3306,db= ' abc ', charset= ' UTF8 ' #port必须写int类型, CharSet must write UTF8
  

cur=coon.cursor () #建立游 Mark
#cur = Coon.cursor (cursor=pymysql.cursors.dictcursor) # Create a cursor, Specifies that the cursor type returns the dictionary type
cur.execute (' select * from Stu; ') #执行sql语句
cur.execute (' insert into Stu (id,name,sex) value ("Zhangsan", "female ");‘) #执行插入语句
coon.commit () #除select语句外, the other statements do not take effect on the database until the commit
res=cur.fetchall () #获取所有返回的结果, It puts every piece of data in the database into a list
#fetchone () returns the first data of the result
Print (RES)
Cur.close () #关闭游标
Coon.close () #关闭连接

---
#还可以先拼接sql语句, and then execute
#username = ' Lisi '
#pwd = ' 123456 '
#sql = ' SELECT * from Nhy where name= '%s ' and pwd = '%s ' '% (username,pwd) #可以先拼接sql语句, then execute
#cur. Execute (SQL)

Novice Learning Python (ix) operation database MySQL

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.