python与mysql交互,插入数据

#encoding=utf-8
# 向学生表中插入一条数据
from pymysql import *

if __name__=='__main__':
    try:
        #创建Connection连接
        conn=connect(host='localhost',port=3306,database='test1',user='root',password='mysql',charset='utf8')
        #获得Cursor对象
        cs1=conn.cursor()
        #执行insert语句,并返回受影响的行数:添加一条学生数据
        # 增加
        count=cs1.execute('insert into students(name) values("张良")')
        # 更新
        count=cs1.execute('update students set name="刘邦" where id=6')
        # 删除
        count=cs1.execute('delete from students where id=6')
        #打印受影响的行数
        print(count)
        #关闭Cursor对象
        cs1.close()
        #提交之前的操作,此处为insert操作
        conn.commit()
    except Exception,e:
        print(e)
    finally:
        #关闭Connection对象
        conn.close()

你可能感兴趣的:(数据库复习,python,mysql,python与mysql交互)