Python MySQL basic operation

Source: Internet
Author: User
Tags python mysql

#链接mysql
#插入数据
Import MySQLdb

conn = MySQLdb.connect (host = ' 127.0.0.1 ', user = ' root ', passwd = ' ', db = ' mytest ')
cur = conn.cursor ()
Reconn = Cur.execute ("INSERT into UserInfo (id,name) value (3, ' Tony ')")
Conn.commit ()
Cur.close ()
Conn.close ()

Print Reconn

#查询数据
Import MySQLdb

conn = MySQLdb.connect (host = ' 127.0.0.1 ', user = ' root ', passwd = ' ', db = ' mytest ')
cur = conn.cursor (cursorclass=mysqldb.cursors.dictcursor) #以字典形式获取数据
cur = conn.cursor () #以元组形式获取数据
#reConn = Cur.execute ("SELECT * from UserInfo")
sql = "SELECT name from userinfo where id =%s"
#sql = "SELECT ID from userinfo where id =%s"
params = 1
#params = ' Dendi '
#reConn = Cur.execute (sql,params)
Reconn = Cur.execute ("SELECT * from UserInfo")
#fetchall把查找到的数据一下拿出来
#fetchone逐个取数据
# data = Cur.fetchall ()
data = Cur.fetchone ()
Print data
data = Cur.fetchone ()
Print data
Cur.close ()
Conn.close ()
# Print Data
Print Reconn

#更新数据
Import MySQLdb

conn = MySQLdb.connect (host = ' 127.0.0.1 ', user = ' root ', passwd = ' ', db = ' mytest ')
cur = conn.cursor ()
sql = "Update userinfo set name = ' AAA ' WHERE id = '%s '"
params = 1
Reconn = Cur.execute (sql,params)
Conn.commit ()
#conn. Rollback ()
Cur.close ()
Conn.close ()

Print Reconn

#删除数据
Import MySQLdb

conn = MySQLdb.connect (host = ' 127.0.0.1 ', user = ' root ', passwd = ' ', db = ' mytest ')
cur = conn.cursor ()
sql = "Delete from userinfo where id = '%s '"
params = 1
Reconn = Cur.execute (sql,params)
Conn.commit ()
#conn. Rollback ()
Cur.close ()
Conn.close ()

Print Reconn



Reference Blog: http://www.cnblogs.com/wupeiqi/articles/4198124.html

Python MySQL basic operation

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.