python学习笔记-MySQL数据库连接相关[Python基础]
内容摘要
import pymssql #引入pymssql模块
server = "localhost"
user = "root"
password = "root"
charset = "cp936"
database = "text_01"
def conn():
connect = pymssql.
文章正文
import pymssql #引入pymssql模块
server = "localhost"
user = "root"
password = "root"
charset = "cp936"
database = "text_01"
def conn():
connect = pymssql.connect(server,user,password,database,charset) #服务器名,账户,密码,数据库名
if connect:
print("连接成功!")
cursor = con.cursor()
# 查询数据库内容
sqlfirst = "select * from datatable"
cursor.execute(sqlfirst)
# 获取查询结果,如果是多条使用:cursor.fetchall()
result = cursor.fetchone()
if __name__ == "__main__":
conn = conn()
以上就是python连接MySQL数据库的基础代码示例,需要注意的是,如果你的数据库中存在中文,必须要设置编码格式为:"cp936"
代码注释
[!--zhushi--]