如何才能连接到数据库并且可查询成功;
import pymysql
def main():
# 创建数据库连接 connection 的对象
conn = pymysql.connect(host='118.xxx.xxx.xxx', port=3306, user='root', password='P@ss1234', database='python001', charset='utf8')
# 创建游标,获得Cursor对象()
cs1 = conn.cursor()
count = cs1.execute('select gender from students group by gender')
# 打印收到影响的行数
print('查询到%d条数据:' % count )
cs1.close()
conn.close()
# config = {
# 'user':'root',
# 'password':'P@ss1234',
# 'host':'118.xxx.xxx.xx',
# 'database':'python001',
# 'port':'3306',
# 'charset':'utf8'
# }
#
# cnx = pymysql.connect(**config)
# cursor = cnx.cursor()
# query = 'select * from goods'
# cursor.execute(query)
# for row in cursor:
# print(row)
# cursor.close()
# cnx.close()
if __name__ == '__main()__':
main()
代码执行后,显示:
E:\learnPython\venv\Scripts\python.exe E:/learnPython/08_数据库/python和MySQL交互/查询数据.py
Process finished with exit code 0
调试时提示:
pydev debugger: CRITICAL WARNING: This version of python seems to be incorrectly compiled (internal generated filenames are not absolute)
pydev debugger: The debugger may still function, but it will work slower and may miss breakpoints.
pydev debugger: Related bug: http://bugs.python.org/issue1666807
Connected to pydev debugger (build 221.5921.27)
pydev debugger: Unable to find real location for:
pydev debugger: Unable to find real location for:
pydev debugger: Unable to find real location for:
以下省略
另外 还是提示需要安装 visual c++build tools ;
重点是:这个数据库连接配置是可用的,使用pycharm 的database ,已经可以看到数据库中的表;
import pymysql
def main():
config = {
'user': 'root',
'password': 'P@ss1234',
'host': '118.xxx.xxx.xxx', # 隐藏了,用这个配置我pycharm都连接上了数据库,见下图
'database': 'python001',
'charset': 'utf8',
}
cnx = pymysql.connect(**config)
cursor = cnx.cursor()
query = 'select * from goods'
cursor.execute(query)
# 获取所有数据应该是 cursor.fetchall(),cursor只是一个游标对象
for row in cursor.fetchall():
print(row)
cursor.close()
cnx.close()
if __name__ == '__main()__':
main()
【以下回答由 GPT 生成】
我可以尝试回答你关于IT方面的问题,请问您有什么具体的问题或需求吗?