您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python数据库编程基础

bubuko 2022/1/25 19:13:17 python 字数 2677 阅读 727 来源 http://www.bubuko.com/infolist-5-1.html

文章介绍python数据库编程基础,列明简单的增删改查操作
数据库编程

1.前期准备

1.1.数据库建库

create database py_test DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

1.2.数据库建表

create table py_test ( id int primary key auto_increment, name varchar(50) not null, age int(10) )character set = utf8;
insert into py_test(name,age) values(‘tansk‘,20);
insert into py_test(name,age) values(‘tanshouke‘,18);

1.3.放行服务器防火墙

systemctl stop firewalld

1.4.开放连接权限

grant all privileges on *.* to ‘root‘@‘%‘ identified by ‘123456‘;
grant all privileges on *.* to ‘root‘@‘localhost‘ identified by ‘123456‘;
flush privileges;

2.数据库连接

2.1.创建数据库连接

import pymysql

class DbUtil(object):
    def __init__(self):
        self.get_conn()

    def get_conn(self):
        # 打开数据库连接
        try:
            conn = pymysql.connect(
                host="192.168.247.13",
                port=3306,
                user="root",
                password="123456",
                database="py_test"
            )
        except Exception as e:
            print("数据库连接报错: %s " % e)
        finally:
            print("数据库连接: ")
            print(conn)
            print("连接类型: ")
            print(type(conn))
            print("")
            return conn

if __name__ == ‘__main__‘:
    getconn = DbUtil.get_conn(self=True)

3.基础的增删改查

3.1.查询

写一个简单的查询语句,实现python与mysql数据库交互

import tansk_01_数据库连接 as DbConn

# 连接数据库
db_conn = DbConn.DbUtil.get_conn(self=True)

# 获取游标
cursor = db_conn.cursor()

# 测试数据库表
test_table = "py_test"
# 执行SQL
cursor.execute("select * from % s;" % test_table)

# 轮询取值
while 1:
    results = cursor.fetchone()
    if results is None:
        # 表示取完结果集
        break
    print(results)
# 关闭游标
cursor.close()
# 关闭数据库连接
db_conn.close()

运行结果:

数据库连接: 
<pymysql.connections.Connection object at 0x00000268A0B7A6D0>
连接类型: 
<class ‘pymysql.connections.Connection‘>

(1, ‘tansk‘, 20)
(2, ‘tanshouke‘, 18)

python数据库编程基础

原文:https://blog.51cto.com/14539398/2677244


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶