mysql与python的交互

##导包
import pymysql

#封装方法
def main():
    #创建mysql连接
    conn = pymysql.connect(host='localhost',port=3306,database='python01',user='root',password='858362',charset='utf8')
    #创建cursor,接受mysql语句并且执行的对象方法
    cursor = conn.cursor()
    #插入10万数据
    for x in range(100000):
        cursor.execute("insert into test_index values('ha - %s','ca - %s')"%(x,x))
    conn.commit()

if __name__ == '__main__':
    main()
import pymysql

def test():
    conn=pymysql.connect(host='localhost',port=3306,database='message',user='root',password='858362',charset='utf8')
    cursor=conn.cursor()

    cursor.execute('select * from classify')

    ret=cursor.fetchall()
    print(ret)
    cursor.execute('select * from news where id = 1')
    r=cursor.fetchone()
    print(r)
    cursor.execute('delete from news where id = 2')
    cursor.execute('select * from news')
    e=cursor.fetchall()
    print(e)
    cursor.execute('update news set name = "张三" where id = 3')
    cursor.execute('select * from news where id = 3')
    a=cursor.fetchone()
    print(a)
    cursor.execute('select * from news where s_news = 1')
    vv=cursor.fetchall()
    print(vv)
    cursor.execute('select * from news where (count>5 and is_delete = "是")')
    ew=cursor.fetchone()
    print(ew)
    conn.commit()
    cursor.close()
    conn.close()

if __name__ == '__main__':
    test()
import pymysql
#
# #创建函数
def main():
    #建立mysql连接
    conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='858362',database='python01',charset='utf8')
    #创建cursor对象,执行sql语句,声明游标对象返回dict
    cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)

    cursor.execute("select * from students")#select * from students
    ret=cursor.fetchone()
    # ret=cursor.fetchall()
    # print(ret)
    # print(ret[4])
    # print(ret[4]['name'])
    print(ret['name'])
    cursor.close()
    conn.close()
if __name__ == '__main__':
    main()

 

转载于:https://www.cnblogs.com/sunzhiqi/p/10075655.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值