[英]Python - Using replace to remove Double Quotes in SQL Query
我想從要通過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())
文件“”,來自operacoes_b2w的第64行” ^語法錯誤:掃描字符串文字時停產
您需要將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"""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.