微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐