我尝试使用简单的脚本python连接到MySQL数据库,但未成功。下面是我的代码,
$lookupDatafiltered = Import-Csv -Path .\lookups_shutdown.csv
$lookupDatafiltered | Group-Object Region, Country, Status | Select-Object @{n='Region';e={$_.Group[0].Region}}, @{n='Country';e={$_.Group[0].Country}},@{n='Status';e={$_.Group[0].Status}}, Count | Sort-Object -Property Region , Country | export-csv -Path "C:\change\Country.csv" -NoTypeInformation
但是我得到这个错误,
[root@vn pyceaudio]# python
Python 2.7.5 (default, Aug 7 2019, 00:51:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>> cnx = mysql.connector.connect(host = 'hostname',database = 'testdb',user = 'test',password = 'test1234')
如果我做错了,请提出建议并告诉我。我是Python的新手,并且仍然在学习。顺便说一下,我正在Centos7中使用Python2.7。
非常感谢您的帮助和建议。赞赏。
此致
答案 0 :(得分:0)
尝试像在本示例https://pynative.com/python-mysql-database-connection/中一样放置try-catch块,并检查异常并将其发布在注释中。
答案 1 :(得分:0)
尝试运行以下代码:
import mysql.connector
from mysql.connector import Error
try:
cnx = mysql.connector.connect(host = 'hostname',database = 'testdb',user = 'test',password = 'test1234')
if cnx.is_connected()://Runs if connection is established
db_Info = cnx.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = cnx.cursor()
cursor.execute("select database();")//executes query using cursor
record = cursor.fetchone()//fetches first data from above cursor
print("Your connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if (cnx.is_connected()):
cursor.close()
cnx.close()
print("MySQL connection is closed")
请参考以下链接:Python Mysql和Python Mysql connection