Python操作数据库

Python操作数据库

import pymysql

# 1.连结MySQL
conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',password='123456',charset='utf8',db='unicom')
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令
# sql="insert into admin(username,password,mobile) values(%s,%s,%s)"
# cursor.execute(sql,['小胡','123456','15874589658'])

# sql="insert into admin(username,password,mobile) values(%(n1)s,%(n2)s,%(n3)s)"
# cursor.execute(sql,{'n1':'小胡','n2':'123456','n3':'15878987485'})

conn.commit()
# 3.关闭
cursor.close()
conn.close()

动态创建数据库

import pymysql

while True:
    user = input("用户名:")
    if user.upper() == 'Q':
        break
    pwd = input("密码:")
    mobile = input("手机号:")
    # 1.连结MySQL
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', charset='utf8', db='unicom')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 2.发送指令(千万不要用字符串格式化去做SQL的拼接,会有安全隐患出现SQL注入)
    sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
    cursor.execute(sql, [user, pwd, mobile])

    conn.commit()
    # 3.关闭
    cursor.close()
    conn.close()

查询数据

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令
cursor.execute("select* from admin where id > %s",[2,])
data_list=cursor.fetchall()		#得到列表里面套字典
for row_dict in data_list:
    print(row_dict)
    
#res=cursor.fetchone()		获取符合条件的第一条数据
#print(res)
# 3.关闭
cursor.close()
conn.close()

删除数据

import pymysql
# 1.连结MySQL
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令
cursor.execute('delete from admin where id=%s',[3,])
conn.commit()
# 3.关闭
cursor.close()
conn.close()

修改数据

import pymysql
# 1.连结MySQL
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令
cursor.execute('update admin set mobile=%s where id=%s',['78541527895',4])
conn.commit()
# 3.关闭
cursor.close()
conn.close()

强调:

  • 在进行新增、删除、修改时,一定要记得commit,不然数据库不变
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值