python创建mysql表和对数据的增删改查

import MySQLdb
#创建mysql数据库连接对象
connect = MySQLdb.connect(
    #链接数据库的host主机地址,默认本地数据库使用localhost或者127.0.0.1进行链接,如果链接远程数据库,需要设置远程主机的ip地址
    host = "localhost",
    #mysql数据库的端口号
    port = 3306,
    #链接数据库的用户名
    user = "root",
    #链接数据库用户名的密码
    passwd = "123456",
    #数据库名称
    db = "student",
    #当数据中要写入中文字符,需要设置两个参数
    use_unicode = True,
    charset="utf8"
)
#创建游标
cursor = connect.cursor()
#创建表
#auto_increment设置id自增
create_table = "create table if not exists stu(id integer primary key auto_increment,name varchar(5),age integer ,phone varchar(11))"

#插入语句
insert_sql = "insert into stu(name,age,phone)values('张三',14,'11011011011')"
#删除语句
delete_sql = "delete from stu where id=1"
#修改
update_sql = "update stu set age=16 where id=2"
#查询
select_sql = "select * from stu"
res = cursor.execute(select_sql)
# print(cursor.fetchone())
# print(cursor.fetchmany(2))
print(cursor.fetchall())

#执行创建表的sql语句
cursor.execute(create_table)
# cursor.execute(insert_sql)
# cursor.execute(update_sql)
# cursor.execute(delete_sql)
connect.commit()
cursor.close()
connect.close()

 MySQLdb与pymysql的用法是一样的。

 

可以关注我的公众号:技术趣谈

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值