python使用mysql

  python利用MySQLdb模块操作MySQL数据库,需要下载模块,主要操作为insert,update,select和delete。简单记录下学习过程,方便复习。

1 MySQLdb模块安装   (python2使用MySQLdb模,python3 使用pymysql模块)

  最开始通过命令行安装,pip install MySQLdb,报错找不到对应模块 ,只能手动下载,注意对应的操作系统和python版本

  下载地址:https://pypi.org/project/MySQL-python/1.2.5/#files

2. 关于中文格式设置:

  1. mysql命令行创建数据库,设置编码为gbk:create databse demo2 character set gbk;  (或者utf8(注意不是utf-8), gb2312)

  2. python代码中连接时设置charset="gbk",代码如下:

conn = MySQLdb.connect(host="localhost", user="root", passwd="", db='demo2', charset='gbk', port=3306)  #和mysql服务端设置格式一样(还可设置为utf8, gb2312)
    cursor = conn.cursor()
    cursor.execute("""create table if not exists t_sales(
                    id int primary key auto_increment not null,
                     nickName varchar(128) not null,
                     color varchar(128) not null,
                      size varchar(128) not null, 
                      comment text not null,
                      saledate varchar(128) not null);""")
    cursor.execute("""insert into t_sales(nickName,color,size,comment,saledate) 
                    values('%s','%s','%s','%s','%s');""" % (nickName, color, size, comment, date))
    conn.commit()
    conn.close()

 

3 相关操作

  主要分为三部分,连接数据库和创建游标,执行sql语句,关闭游标和数据库连接

connection = MySQLdb.connect(host='127.0.0.1', user='root',passwd='', db='trail') # 连接数据库
cur = connection.cursor()  # 创建游标
reCount = cur.execute('select name from admin')  执行sql语句
cur.close()   #关闭游标
connection.close()  # 关闭数据库连接

  插入(insert)

  删除delete

  更新 update

执行多条插入语句    

获取数据的多种方式,执行的结果可以看到返回数据为元组,且里面再嵌套一个元组

以字典形式拿到数据,使用下面参数建立游标,通过返回数据可以看出返回数据为元组,但里面再嵌套一个字典

cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) # fectall返回数据为包含字典的复合元组

 

posted @ 2024-09-21 14:21  silence_cho  阅读(86)  评论(0)    收藏  举报