我是Python的新手,我正在尝试创建一个通过PyMySQL将数据保存到数据库的表单,但是我在连接数据库时遇到了问题。我已经按照示例代码(我的版本在下面)并彻底检查了所有语法和语音标记,但仍然出现以下错误。
File "c:\Users\Nimrod\Nimrod Dropbox\Dropbox\Nimrodsky\Python\Adiabatic Equation\DB connect with PyMySQL.py", line 10, in <module> charset='utf8')
File "C:\ProgramData\Anaconda3\lib\site-packages\pymysql\__init__.py", line 90, in Connect return Connection(*args, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\pymysql\connections.py", line 706, in __init__ self.connect()
File "C:\ProgramData\Anaconda3\lib\site-packages\pymysql\connections.py", line 922, in connect self.host_info = "socket %s:%d" % (self.host, self.port)
TypeError: %d format: a number is required, not str
import pymysql
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='sql8.freesqldatabase.com',
port='3306',
user='********',
password='**********',
db='*********',
charset='utf8')
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `client` (`ID`, `client_name`, `client_address_1`, `client_address_2`, `client_address_3`, `client_postcode`, `occupier_name`, `install_address_1`, `install_address_2`, `install_address_3`, `install_postcode`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
cursor.execute(sql, ('1', 'Terry Jones', '10 DOwning Street', 'Guildford','Surrey', 'GU1 5HA', 'Paul Smith', 'Wimbledon Hill', 'Wimbledon', 'London', 'SW19 5QT'))
#connection is not autocommit by default. So you must commit to save
#your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `occupier_name` FROM `client` WHERE `client_name`=%s"
cursor.execute(sql, ('Terry Jones',))
result = cursor.fetchone()
print (result)
finally:
connection.close
答案 0 :(得分:5)
端口必须是整数:port=3306
。