python获取mysql数据库数据

it2022-05-07  43

1、mysql数据库表例子   

    创建数据库表    CREATE DATABASE testDB;

    USE testDB;

    CREATE TABLE student (       -> id INT NOT NULL AUTO_INCREMENT,       -> name VARCHAR(20) NOT NULL,       -> age INT NOT NULL,       -> PRIMARY KEY(id)       -> );

    INSERT INTO student(name,age) VALUES ('xiaoming',16),('zhangsan',18);

2、python连接mysql

  1)安装PyMySQL模块

    pip install PyMySQL

  2)python获取mysql数据

    

1 #!/usr/bin/python 2 #-*- coding:utf-8 -*- 3 4 import pymysql 5 6 host="localhost" 7 user="root" 8 password="123456" 9 database="testDB" 10 11 #打开数据库连接 12 test_db = pymysql.connect(host,user,password,database) 13 #创建一个游标对象 14 cursor = test_db.cursor() 15 #执行SQL查询 16 cursor.execute("SELECT * FROM student") 17 #获取全部匹配数据 18 student_info = cursor.fetchall() 19 #关闭数据库 20 test_db.close() 21 22 print(student_info)

  3)输出结果

    ((1, 'xiaoming', 16), (2, 'zhangsan', 18))

转载于:https://www.cnblogs.com/longBlogs/p/10993617.html


最新回复(0)