PyMySql模块增删查改基本操作

代码如下:

##设置编码格式为utf8避免中文乱码
#encoding:utf8
import pymysql


##查询
def select():
    conn = pymysql.connect(user='root', passwd='你的密码',
                     host='localhost', db='test',charset='utf8')
    cur = conn.cursor()
    cur.execute("SELECT * FROM user")
    for r in cur:
          print("row_number:" , (cur.rownumber) )        
          print("id:"+str(r[0])+" name:"+str(r[1])+" password:"+str(r[2])) 
    cur.close()    
    conn.close()

##插入
def insert(name,pwd):
    conn = pymysql.connect(user='root', passwd='你的密码',
                     host='localhost', db='test',charset='utf8')
    cur = conn.cursor()
    sql= "INSERT INTO user (Name,Password) VALUES ('"+name+"','"+pwd+"')"
    print(sql)
    sta=cur.execute(sql)
    if sta==1:
        print('Done')
    else:
        print('Failed')   
    conn.commit()
    cur.close()    
    conn.close()

##更新
def update(name,pwd):
    conn = pymysql.connect(user='root', passwd='你的密码',
                     host='localhost', db='test',charset='utf8')
    cur = conn.cursor()
    sql= "UPDATE USER SET PASSWORD='"+pwd+"' WHERE NAME='"+name+"'"
    print(sql)
    sta=cur.execute(sql)
    if sta==1:
        print('Done')
    else:
        print('Failed')   
    conn.commit()
    cur.close()    
    conn.close()

##删除
def delete(name):
    conn = pymysql.connect(user='root', passwd='你的密码',
                     host='localhost', db='test',charset='utf8')
    cur = conn.cursor()
    sql = "DELETE FROM USER WHERE Name='"+name+"'"
    print(sql)
    sta=cur.execute(sql)
    if sta==1:
        print('Done')
    else:
        print('Failed')   
    conn.commit()
    cur.close()    
    conn.close()

##调用函数进行操作即可
 注意:

1.连接字符串按照个人实际填写

2.连接字符串 指明了编码格式,避免中文变"?"

3.sql语句可以先利用SQLyog等软件测试是否能够运行,然后拼接一下字符串会减少出错几率。每个函数我都输出了sql语句。

你可能感兴趣的:(Python)