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)

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...