美文网首页
Python MySQLdb的基本使用方法

Python MySQLdb的基本使用方法

作者: 失控的胖纸 | 来源:发表于2020-04-10 09:00 被阅读0次

以新建数据库、新建表、插入数据为例,更新、删除、查询等操作只要替换对应sql语句即可

import MySQLdb

#打开数据库连接
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306,charset='utf8')

#获取操作游标
cursor = conn.cursor()

try:
    sql1 = "create database if not exists testdb"  #新建数据库
    cursor.execute(sql1) #执行sql语句
    conn.select_db('testdb')  #使用testdb库
    sql2 = "create table if not exists student(id int(8) ,username varchar(50) character set utf8 default null) ENGINE=InnoDB default charset=utf8"
    cursor.execute(sql2)
    sql3 = "insert into student values(2,'张三')"
    cursor.execute(sql3)

    conn.commit()  #提交到数据库执行
    cursor.close()   #关闭游标

except:
    conn.rollback()  #回滚

conn.close()   #关闭数据库连接

执行结果:


image.png

相关文章

网友评论

      本文标题:Python MySQLdb的基本使用方法

      本文链接:https://www.haomeiwen.com/subject/etklmhtx.html