由于插入PostgreSQL数据库的数据中存在“'”,因此会发生错误。错误如下:
psycopg2.ProgrammingError:“S”LINE 1处或附近的语法错误: ... ice_type)VALUES('7055598','CHEE KONG POI','HEE'S ENGINEER ......
有解决这个问题的方法吗?目前的代码如下:
def store(license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line, work_type):
statement = (
"INSERT INTO service_reviews_serviceprovider" \
" (license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line, service_type)" \
" VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', 'electrician');"
).format(license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line)
print(statement)
cur.execute(statement)
cur.connection.commit()
return None
答案 0 :(得分:3)
这是在创建SQL语句时不使用字符串替换的原因之一。改为使用参数:
statement = (
"INSERT INTO service_reviews_serviceprovider"
" (license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line, service_type)"
" VALUES(%s, %s, %s, %s, %s, %s, %s, 'electrician');"
)
cur.execute(
statement, (license_number, individual_name, corporate_name, reg_address, email_address, land_line, hand_phone_line)
)
请注意,这会将整个参数集作为单个元组参数发送到db api,它会根据需要进行引用。
除了解决问题之外,这还可以防止SQL注入,这是始终以这种方式执行此操作的主要原因。
答案 1 :(得分:1)
使用多行字符串Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim year As Integer = Today.Year
For i As Integer = 1915 To year
comboBox.Items.Add(CStr(i))
Next
End Sub
Private Sub comboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comboBox.SelectedIndexChanged
Dim yearToday As Integer = Today.Year
Dim year As Integer 'stores selected items from combobox
Dim age As Integer
year = CInt(comboBox.SelectedItem)
age = yearToday - year
txtBox.Text = age.ToString 'displays age on textbox
End Sub
End Class
。使用"""
将参数传递给查询。将要插入的值转换为cursor.execute
,然后将其传递给tuple
,以避免混乱的字符串构建和难以阅读的代码。
cursor.execute