Python中pymysql基本使用

 

Python中pymysql模块通过获取mysql数据库命令行游标执行数据库命令来进行数据库操作

  优点:操作数据库语句所见即所得,执行了什么数据库语句都很清楚

  缺点:操作繁琐,代码量多

 

 

1. pymysql的基本使用

# -*- coding:utf-8 -*-
# Author:Wong Du

import pymysql

# 创建链接,相当于建立一个socket
conn = pymysql.Connection(host='10.0.0.100', port=3306, user='root', passwd='123456', db='testdb')

# 建立游标,相当于进入 mysql> 命令操作界面
cursor = conn.cursor()

# 建表,和mysql命令行操作一样
try:
    create_table = cursor.execute('''create table student(
                                  id int not null primary key auto_increment,
                                  name char(32) not null,
                                  register_date date not null DEFAULT "2018-05-09" );
                                  ''')
except pymysql.err.InternalError as e:
    # print(type(e))
    print("\033[31;1m%s; Do nothing...\033[0m" %e)

# 插入数据
insert = cursor.execute('insert into student (name,register_date) values("junry", "2017-03-14");')
insert2 = cursor.execute('insert into student (name,register_date) values("hongfa", "2015-03-14");')
insert3 = cursor.execute('insert into student (name,register_date) values("jinglin", "2016-03-14");')

# 查看表数据
select = cursor.execute('select * from student;')
for line in cursor.fetchall():
    print(line)

# 修改表数据
update = cursor.execute('update student set name="junwei" where id=1')
select2 = cursor.execute('select * from student;')
print(cursor.fetchone())

# 删除表数据
delete = cursor.execute('delete from student;')
select3 = cursor.execute('select * from student;')
if cursor.fetchall():
    print(cursor.fetchall())
else:
    print("This is a empty table...")

# 提交
conn.commit()

cursor.close()  # 关闭游标
conn.close()    # 关闭连接


# 等等 等等。。。

 

循环插入数据

# -*- coding:utf-8 -*-
# Author:Wong Du

import pymysql

# 建立连接
conn = pymysql.Connect(host='10.0.0.100', port=3306, user='root', passwd='123456', db='testdb')

# 创建游标
cursor = conn.cursor()

# 循环插入列表
many_list = [
    ('zhangsan', '2011-11-11'),
    ('lisi', '2012-11-11'),
    ('wangwu', '2022-10-09'),
]

# 循环插入(插入多条内容)
cursor.executemany("insert into student (name, register_date) VALUE(%s, %s);", many_list)

# 修改游标位置
cursor.scroll(1, mode='relative')   # 相对移动,默认为relative
cursor.scroll(1, mode='absolute')   # 绝对移动

# fetchone()获取一行数据、fetchmany(num)获取指定行数据、fetchall()获取所有行数据
cursor.execute("select * from student;")
for line in cursor.fetchall():
    print(line)

# 清楚student表的数据
cursor.execute("delete from student;")


# 提交
conn.commit()

cursor.close()  # 关闭游标
conn.close()    # 关闭连接

 

转载于:https://www.cnblogs.com/Caiyundo/p/9578925.html

你可能感兴趣的:(python,数据库)