pymysql模块连接数据库
Python2中使用的是mysqldb连接数据库,而在Python3中则使用pymysql模块连接数据库。
pymyslq安装
在终端命令行执行:
pip install pymysql
pymysql的使用-创建一个表(tablename)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 导入pymysql模块
import pymysql
import os,sys
try:
# 连接database
conn = pymysql.connect(host="127.0.0.1",user="root",passwd="shiyanshi#123",db="dbtest")
# 其中host是数据库服务器的IP地址,user是mysql用户,passwd是mysql用户的登录密码,db是要连接的数据库名称
except Exception as e:
print(e)
sys.exit()
# 创建一个可以执行sql语句的光标对象
cursor = conn.cursor()
# 定义sql语句
sql = "create table tablename (id int (100), name varchar (30));"
# 执行sql语句
cursor.execute(sql)
# 关闭光标
cursor.close()
# 关闭数据库连接
conn.close()
查询刚才创建的表(tablename)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 导入pymysql模块
import pymysql
import os,sys
try:
# 连接database
conn = pymysql.connect(host="127.0.0.1",user="root",passwd="shiyanshi#123",db="dbtest")
# 其中host是数据库服务器的IP地址,user是mysql用户,passwd是mysql用户的登录密码,db是要连接的数据库名称
except Exception as e:
print(e)
sys.exit()
# 创建一个可以执行sql语句的光标对象
cursor = conn.cursor()
# 定义sql语句
sql = "show tables;"
# 执行sql语句
cursor.execute(sql)
# 返回查询结果
data = cursor.fetchall()
# 关闭光标
cursor.close()
# 关闭数据库连接
conn.close()
print(data)
终端返回:
(('tablename',),)