我想从要通过Python导出信息的数据库中删除双引号,但是在运行查询时遇到以下错误:
我在过程中使用了应该是正确的替换,但是我没有成功...
# Libraries
import csv
import logging
import os
import gcloud
from gcloud import storage
from google.cloud import bigquery
from oauth2client.client import GoogleCredentials
import json
import pyodbc
from datetime import datetime
try:
script_path = os.path.dirname(os.path.abspath(__file__)) + "/"
except:
script_path = "key.json"
#Bigquery Credentials and settings
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = script_path
database='xxx'
uid = 'xxx'
pwd = 'xxx'
server = '0.0.0.0'
driver = "DRIVER={SQL Server};server=" + server + ";database=" + database + ";uid=" + uid + ";pwd=" + pwd
print(driver)
# connecting to the DB
db = pyodbc.connect(driver)
cursor = db.cursor()
tabela = 'test'
SQLview = "select replace(replace(col0,';','|'),'"','') as col0, \
replace(replace(col1,';','|'),'"','') as col1, \
replace(replace(col2,';','|'),'"','') as col2, \
replace(replace(col3,';','|'),'"','') as col3, \
replace(replace(col4,';','|'),'"','') as col4
from test"
data = datetime.today().strftime('%Y%m%d%H%M%S')
filename = tabela + '_' + data + '.csv'
folder = "C:\\Users\\me\\Documents\\"
# Creating CVS file
cursor.execute(SQLview)
with open(folder + filename, 'w', newline= '', encoding = 'utf-8') as f:
writer = csv.writer(f, delimiter=';')
writer.writerow([ i[0] for i in cursor.description ])
writer.writerows(cursor.fetchall())
文件“”,第64行 来自Operacoes_b2w” ^ SyntaxError:扫描字符串文字时会停工
答案 0 :(得分:1)
您需要将SQL查询用三引号而不是单引号引起来,因为它会将其中的"
误认为是结束字符串。代替这个:
SQLview = "select replace(replace(col0,';','|'),'"','') as col0, \
replace(replace(col1,';','|'),'"','') as col1, \
replace(replace(col2,';','|'),'"','') as col2, \
replace(replace(col3,';','|'),'"','') as col3, \
replace(replace(col4,';','|'),'"','') as col4
from test"
执行以下操作:
SQLview = """select replace(replace(col0,';','|'),'"','') as col0, \
replace(replace(col1,';','|'),'"','') as col1, \
replace(replace(col2,';','|'),'"','') as col2, \
replace(replace(col3,';','|'),'"','') as col3, \
replace(replace(col4,';','|'),'"','') as col4
from test"""