使用Python连接MySQL数据库并查找表信息
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]