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;
@H_502_2@2.数据库连接2.1.创建数据库连接import pyMysqLclass 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 connif __name__ == '__main__': getconn = DbUtil.get_conn(self=True)
@H_502_2@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"# 执行sqlcursor.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数据库编程基础全部内容,希望文章能够帮你解决python数据库编程基础所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)