import subprocess
import pyodbc
c = dbconn.cursor()
server = r".\SQLEXPRESS01"
database = "test"
dbconn = pyodbc.connect("driver={SQL Server Native Client 11.0};server=" + server + "; database="+ database +"; trusted_connection=yes;",
autocommit=True)
\\unable to write code for table name loop \\
out_path = f"D:\\Projects\\ReferenceModel\\DataFiles\\IN_Download\\Format_Files\\{table_name}.fmt"
bcp_command = f"bcp {table_name} format nul -c -t, -f {out_path} -S {server} -d {database} -T"
cmd_args = f"/c {bcp_command}"
subprocess.call(["cmd.exe", cmd_args])我正在尝试使用pyodbc从数据库test中的所有表中提取表名(假设50个表),但我在这样做时遇到了困难。我试图从数据库(test)中获取表名,这样我就不必对其进行硬编码(就像我现在所做的那样)。有人能帮我处理密码吗?
注意:尝试使用游标命令移动我的数据库中的所有表名。
发布于 2020-06-23 09:51:00
您应该能够直接调用bcp.exe,而不是尝试使用cmd.exe /c。这应该是你需要的..。
import subprocess
import pyodbc
server = r".\SQLEXPRESS01"
database = "test"
connection = f"driver={{SQL Server Native Client 11.0}};server={server};database={database};trusted_connection=yes;"
dbconn = pyodbc.connect(connection, autocommit=True)
cursor = dbconn.cursor()
cursor.execute("SELECT name FROM sys.tables")
for row in cursor:
table_name = row[0]
out_path = f"D:\\Projects\\ReferenceModel\\DataFiles\\IN_Download\\Format_Files\\{table_name}.fmt"
args = [ "bcp.exe", f"{database}.dbo.{table_name}", "format", "nul", "-c", "-t,", f"-f{out_path}", f"-S{server}", "-T"]
subprocess.call(args)https://stackoverflow.com/questions/62527576
复制相似问题