简体   繁体   English

使用 Visual Studio Code 将数据导入 SQL 服务器

[英]Importing Data into SQL Server with Visual Studio Code

I am attempting to use Visual Studio Code(VSC) to import a csv file into SQL Server.我正在尝试使用 Visual Studio Code(VSC) 将 csv 文件导入 SQL 服务器。

I can access SQL Server in VSC using the MSSQL extension.我可以使用 MSSQL 扩展访问 VSC 中的 SQL 服务器。 I am able to select, add columns, create tables ect... I can use python to load and manipulate the csv file.我能够 select、添加列、创建表等...我可以使用 python 加载和操作 csv 文件。

However, I don't know how to connect the Python and the SQL scripts, or alternatively, how to use an sql script to query a csv file on my local computer. However, I don't know how to connect the Python and the SQL scripts, or alternatively, how to use an sql script to query a csv file on my local computer.

One option is to just use Python , but I've had some trouble successfully setting up that connection.一种选择是仅使用 Python ,但我在成功设置该连接时遇到了一些麻烦。

I don't know about a VS Code specific tool but if you can run SQL scripts then you can look at OPENROWSET .我不知道 VS Code 特定工具,但如果您可以运行 SQL 脚本,那么您可以查看OPENROWSET Example F is probably a close match for what you are looking for but there are lots of options with this command to get exactly what you want.示例 F 可能与您要查找的内容非常匹配,但是此命令有很多选项可以准确获取您想要的内容。

INSERT INTO MyTable SELECT a.* FROM
OPENROWSET (BULK N'D:\data.csv', FORMATFILE =
    'D:\format_no_collation.txt', CODEPAGE = '65001') AS a;

first try to install mysql connector using this- pip install mysql-connector-python首先尝试使用此安装 mysql 连接pip install mysql-connector-python

after that use import mysql.connector to import the connector之后使用import mysql.connector导入连接器

Then connect your database using this-然后使用这个连接你的数据库 -

myconn = mysql.connector.Connect(user='root',password="1234567890",database="world",auth_plugin='mysql_native_password')

where password is your mysql password and database is your name of database you want to connect其中密码是您的 mysql 密码,数据库是您要连接的数据库的名称

suppose you want to fetch all rows from your selected table-假设您想从所选表中获取所有行-

myconn = mysql.connector.Connect(user='root',password="1234567890",database="world")
cur = myconn.cursor()
cur.execute("Select * from emptab")
allrows = cur.fetchall()
print(allows)

this would generate result like that-这会产生这样的结果-

(1001, 'RamKumar', 10000)
(1002, 'Ganesh Kumar', 1000)
(1003, 'Rohan', 3450)
(1004, 'Harish Kumar', 56000)
(1005, 'Mohit', 12000)
(1006, 'Harish Nagar', 56000)

to convert above data to CSV form first convert it into an pandas data frame-要将上述数据转换为 CSV 形式,首先将其转换为 pandas 数据帧-

df = pd.DataFrame(allrows)
df.columns = ['empno','name','salary']

this would convert data into pandas df and with columns above这会将数据转换为 pandas df 和上面的列

at last use最后使用

df_final.to_csv(r'final.csv', index = False)

like command to save result to csv form像命令将结果保存到 csv 表格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM