Python连接MySQL数据库并查找表信息
作者:白芷加茯苓
本文主要介绍了Python连接MySQL数据库并查找表信息,通过使用Python中的MySQL Connector模块,连接到MySQL服务器并执行SQL查询语句,可以获取表的结构、列信息、行数据等,感兴趣的可以了解一下
1.导入MySQLdb包
import MySQLdb
如果你的PyCharm中没有MySQLdb,就从Setting-》Project Interpreter查找并下载


2.在MySQL中新建一个连接,取名为python ,再新建一个测试表,取名为examples

CREATE TABLE IF NOT EXISTS examples (
id int(11) NOT NULL AUTO_INCREMENT,
description varchar(45),
PRIMARY KEY (id)
);
INSERT INTO examples(description) VALUES ("Hello World");
INSERT INTO examples(description) VALUES ("MySQL Example");
INSERT INTO examples(description) VALUES ("Flask Example");
3.书写Python代码
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host
user="root", # username
passwd="root", # password
db="python") # name of the database
# Create a Cursor object to execute queries.
cur = db.cursor()
# Select data from table using SQL query.
cur.execute("SELECT * FROM examples")
# print the first and second columns
for row in cur.fetchall() :
print row[0], " ", row[1]
到此这篇关于Python连接MySQL数据库并查找表信息 的文章就介绍到这了,更多相关Python连接MySQL并查找表信息 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
