質問編集履歴
5
感想追記とか
test
CHANGED
File without changes
|
test
CHANGED
@@ -18,8 +18,8 @@
|
|
18
18
|
こんな方法しかないのでしょうか。
|
19
19
|
他に良い方法等ありましたら教えて下さい。
|
20
20
|
|
21
|
-
とりあえず、to_sqlで出力する例とADOつかってRecorsSetでappendする例と
|
21
|
+
とりあえず、to_sqlで出力する例1とADOつかってRecorsSetでappendする例2と
|
22
|
-
リンク先に提示してあったto_excelからのinsert intoの例を比較してみました。
|
22
|
+
リンク先に提示してあったto_excelからのinsert intoの例3を比較してみました。
|
23
23
|
|
24
24
|
コードは以下の通りです。
|
25
25
|
```python
|
@@ -184,9 +184,9 @@
|
|
184
184
|
|
185
185
|
```
|
186
186
|
結果は
|
187
|
-
1が22秒
|
187
|
+
例1が22秒
|
188
|
-
2が35秒
|
188
|
+
例2が35秒(やってみたがto_sqlより遅いとは…何かまずい所があるのかな?)
|
189
|
-
3が6秒
|
189
|
+
例3が6秒
|
190
190
|
でした。
|
191
191
|
|
192
192
|
やはり、リンク先の内容の通りということなのでしょうか。
|
4
余計なコードカット
test
CHANGED
File without changes
|
test
CHANGED
@@ -242,9 +242,6 @@
|
|
242
242
|
|
243
243
|
return engine
|
244
244
|
|
245
|
-
#import os
|
246
|
-
#os.environ['NLS_LANG'] = "utf-8"
|
247
|
-
|
248
245
|
engine = alchemy_engine(r"D:\study\Python\sss.accdb")
|
249
246
|
|
250
247
|
gdf=gpd.read_file(path_read_shp,encode='utf-8')
|
3
誤記修正
test
CHANGED
File without changes
|
test
CHANGED
@@ -249,7 +249,6 @@
|
|
249
249
|
|
250
250
|
gdf=gpd.read_file(path_read_shp,encode='utf-8')
|
251
251
|
df=pd.DataFrame(gdf.drop('geometry',axis=1))
|
252
|
-
df=df[:3]
|
253
252
|
df.to_sql('shape_test', engine, if_exists='replace', index=False)
|
254
253
|
|
255
254
|
```
|
2
シェープファイルからの例を記載
test
CHANGED
File without changes
|
test
CHANGED
@@ -191,3 +191,65 @@
|
|
191
191
|
|
192
192
|
やはり、リンク先の内容の通りということなのでしょうか。
|
193
193
|
データの量を増やしてどう変わるかについては、また検証してみます。
|
194
|
+
|
195
|
+
あとシェープファイルからということでしたので
|
196
|
+
シェープファイルからの登録の例として書いてみたコードも記載しておきます。
|
197
|
+
|
198
|
+
```python
|
199
|
+
import osgeo.ogr as ogr
|
200
|
+
from sqlalchemy.types import Float,Integer,String,Text,DateTime
|
201
|
+
|
202
|
+
path_read_shp=r"D:\study\Python\AAAA.shp"
|
203
|
+
|
204
|
+
driver = ogr.GetDriverByName("ESRI Shapefile")
|
205
|
+
data_source = driver.Open(path_read_shp)
|
206
|
+
layer = data_source.GetLayer(0)
|
207
|
+
layer_defn = layer.GetLayerDefn()
|
208
|
+
dtypes={}
|
209
|
+
for column in range(layer_defn.GetFieldCount()):
|
210
|
+
field_defn=layer_defn.GetFieldDefn(column)
|
211
|
+
field_name=field_defn.GetName()
|
212
|
+
if field_defn.GetType() == ogr.OFTInteger:
|
213
|
+
dtypes[field_name]=Integer
|
214
|
+
elif field_defn.GetType() == ogr.OFTInteger64:
|
215
|
+
dtypes[field_name]=Integer
|
216
|
+
elif field_defn.GetType() == ogr.OFTReal:
|
217
|
+
dtypes[field_name]=Float
|
218
|
+
elif field_defn.GetType() == ogr.OFTString:
|
219
|
+
if field_defn.GetWidth()<=255:
|
220
|
+
dtypes[field_name]=String(field_defn.GetWidth())
|
221
|
+
else:
|
222
|
+
dtypes[field_name]=Text
|
223
|
+
elif field_defn.GetType() == ogr.OFTDate :
|
224
|
+
dtypes[field_name]=DateTime
|
225
|
+
|
226
|
+
data_source.Destroy()
|
227
|
+
|
228
|
+
import pandas as pd
|
229
|
+
import geopandas as gpd
|
230
|
+
from urllib.parse import quote_plus
|
231
|
+
from sqlalchemy import create_engine
|
232
|
+
|
233
|
+
# sqlalchemyのengineを作成
|
234
|
+
def alchemy_engine(db_path):
|
235
|
+
con_str = "DRIVER=" + \
|
236
|
+
"{Microsoft Access Driver (*.mdb, *.accdb)};" + \
|
237
|
+
f"DBQ={db_path};"
|
238
|
+
con_str = quote_plus(con_str)
|
239
|
+
engine = create_engine(
|
240
|
+
f"access+pyodbc:///?odbc_connect={con_str}",
|
241
|
+
echo=True)
|
242
|
+
|
243
|
+
return engine
|
244
|
+
|
245
|
+
#import os
|
246
|
+
#os.environ['NLS_LANG'] = "utf-8"
|
247
|
+
|
248
|
+
engine = alchemy_engine(r"D:\study\Python\sss.accdb")
|
249
|
+
|
250
|
+
gdf=gpd.read_file(path_read_shp,encode='utf-8')
|
251
|
+
df=pd.DataFrame(gdf.drop('geometry',axis=1))
|
252
|
+
df=df[:3]
|
253
|
+
df.to_sql('shape_test', engine, if_exists='replace', index=False)
|
254
|
+
|
255
|
+
```
|
1
サンプルコード追記
test
CHANGED
File without changes
|
test
CHANGED
@@ -18,6 +18,176 @@
|
|
18
18
|
こんな方法しかないのでしょうか。
|
19
19
|
他に良い方法等ありましたら教えて下さい。
|
20
20
|
|
21
|
+
とりあえず、to_sqlで出力する例とADOつかってRecorsSetでappendする例と
|
22
|
+
リンク先に提示してあったto_excelからのinsert intoの例を比較してみました。
|
23
|
+
|
24
|
+
コードは以下の通りです。
|
25
|
+
```python
|
26
|
+
import pandas as pd
|
27
|
+
from urllib.parse import quote_plus
|
28
|
+
from sqlalchemy import create_engine
|
29
|
+
from sqlalchemy import types
|
30
|
+
import time
|
31
|
+
import os
|
32
|
+
import math
|
33
|
+
|
34
|
+
def alchemy_engine(db_path):
|
35
|
+
con_str = "DRIVER=" + \
|
36
|
+
"{Microsoft Access Driver (*.mdb, *.accdb)};" + \
|
37
|
+
f"DBQ={db_path};"
|
38
|
+
con_str = quote_plus(con_str)
|
39
|
+
engine = create_engine(
|
40
|
+
f"access+pyodbc:///?odbc_connect={con_str}",
|
41
|
+
echo=True)
|
42
|
+
|
43
|
+
return engine
|
44
|
+
|
45
|
+
path_access=r"D:\work\study\python\pandas_access\orderby.accdb"
|
46
|
+
engine = alchemy_engine(path_access)
|
47
|
+
|
48
|
+
data_a=[]
|
49
|
+
data_b=[]
|
50
|
+
data_c=[]
|
51
|
+
data_d=[]
|
52
|
+
data_e=[]
|
53
|
+
for i in range(30000):
|
54
|
+
data_a.append(i)
|
55
|
+
data_b.append(float(i))
|
56
|
+
data_c.append(str(i))
|
57
|
+
data_d.append(None)
|
58
|
+
data_e.append(str(i))
|
59
|
+
|
60
|
+
df=pd.DataFrame({'A':data_a,'B':data_b,'C':data_c,'D':data_d,'E':data_e})
|
61
|
+
dtypes={'A':types.Integer,'B':types.Float,'C':types.String(10),'D':types.DateTime,'E':types.Text}
|
62
|
+
|
63
|
+
start_time = time.perf_counter()
|
64
|
+
df.to_sql('testtable', engine, if_exists='replace', index=False,dtype=dtypes)
|
65
|
+
end_time = time.perf_counter()
|
66
|
+
|
67
|
+
elapsed_time = end_time - start_time
|
68
|
+
print(elapsed_time)
|
69
|
+
|
70
|
+
import win32com.client
|
21
71
|
|
22
72
|
|
73
|
+
def insert_to_access(path,df,table,dtypes):
|
74
|
+
dic_data_type = {
|
75
|
+
types.DateTime:"DATETIME",
|
76
|
+
types.Float:"DOUBLE",
|
77
|
+
types.Integer:"INTEGER",
|
78
|
+
types.Text: "LONGCHAR",
|
79
|
+
types.String:"VARCHAR",
|
80
|
+
}
|
81
|
+
conn = win32com.client.Dispatch(r'ADODB.Connection')
|
23
82
|
|
83
|
+
DSN ='Provider=Microsoft.ACE.OLEDB.12.0;Data Source=' + path + ';'
|
84
|
+
|
85
|
+
conn.Open(DSN)
|
86
|
+
|
87
|
+
sql="DROP TABLE [" + table + "]"
|
88
|
+
try:
|
89
|
+
conn.Execute(sql)
|
90
|
+
except:
|
91
|
+
pass
|
92
|
+
|
93
|
+
sql="CREATE TABLE [" + table + "] ("
|
94
|
+
for column in df.columns:
|
95
|
+
if isinstance(dtypes[column], types.String):
|
96
|
+
sql += column + ' ' + dic_data_type[types.String]
|
97
|
+
sql += '(' + str(dtypes[column].length) + ')'
|
98
|
+
else:
|
99
|
+
sql += column + ' ' + dic_data_type[dtypes[column]]
|
100
|
+
sql += ','
|
101
|
+
sql=sql[:-1]+ ')'
|
102
|
+
|
103
|
+
conn.Execute(sql)
|
104
|
+
|
105
|
+
rs = win32com.client.Dispatch(r'ADODB.Recordset')
|
106
|
+
rs.CursorLocation = 3 # adUseClient
|
107
|
+
rs.LockType = 4 # adLockBatchOptimistic
|
108
|
+
rs.Properties.Item("Append-Only Rowset").Value= True
|
109
|
+
rs.Open("SELECT * FROM [" + table + "]",conn)
|
110
|
+
|
111
|
+
l=len(df.columns)
|
112
|
+
count=0
|
113
|
+
for row in df.itertuples(name=None):
|
114
|
+
count+=1
|
115
|
+
rs.AddNew()
|
116
|
+
for i in range(l):
|
117
|
+
if not row[i+1] is None:
|
118
|
+
if isinstance(row[i+1],float) or isinstance(row[i+1],int):
|
119
|
+
if not math.isnan(row[i+1]):
|
120
|
+
rs.Fields.Item(i).Value=row[i+1]
|
121
|
+
else:
|
122
|
+
rs.Fields.Item(i).Value=row[i+1]
|
123
|
+
if count % 5000 ==0:
|
124
|
+
rs.UpdateBatch()
|
125
|
+
if count % 5000 != 0:
|
126
|
+
rs.UpdateBatch()
|
127
|
+
rs.Close()
|
128
|
+
conn.Close()
|
129
|
+
|
130
|
+
def insert_to_access2(path,df,table,dtypes):
|
131
|
+
dic_data_type = {
|
132
|
+
types.DateTime:"DATETIME",
|
133
|
+
types.Float:"DOUBLE",
|
134
|
+
types.Integer:"INTEGER",
|
135
|
+
types.Text: "LONGCHAR",
|
136
|
+
types.String:"VARCHAR",
|
137
|
+
}
|
138
|
+
conn = win32com.client.Dispatch(r'ADODB.Connection')
|
139
|
+
DSN ='Provider=Microsoft.ACE.OLEDB.12.0;Data Source=' + path + ';'
|
140
|
+
conn.Open(DSN)
|
141
|
+
|
142
|
+
sql="DROP TABLE [" + table + "]"
|
143
|
+
try:
|
144
|
+
conn.Execute(sql)
|
145
|
+
except:
|
146
|
+
pass
|
147
|
+
|
148
|
+
sql="CREATE TABLE [" + table + "] ("
|
149
|
+
for column in df.columns:
|
150
|
+
if isinstance(dtypes[column], types.String):
|
151
|
+
sql += column + ' ' + dic_data_type[types.String]
|
152
|
+
sql += '(' + str(dtypes[column].length) + ')'
|
153
|
+
else:
|
154
|
+
sql += column + ' ' + dic_data_type[dtypes[column]]
|
155
|
+
sql += ','
|
156
|
+
sql=sql[:-1]+ ')'
|
157
|
+
|
158
|
+
conn.Execute(sql)
|
159
|
+
|
160
|
+
xlsx_path = os.path.splitext(path)[0] + '.xlsx'
|
161
|
+
df.to_excel(xlsx_path, index=False)
|
162
|
+
sql = f"""\
|
163
|
+
INSERT INTO [{table}]
|
164
|
+
SELECT * FROM [Sheet1$] IN "{xlsx_path}" 'Excel 12.0 Macro;HDR=Yes'
|
165
|
+
"""
|
166
|
+
|
167
|
+
conn.Execute(sql)
|
168
|
+
os.remove(xlsx_path)
|
169
|
+
conn.Close()
|
170
|
+
|
171
|
+
|
172
|
+
start_time = time.perf_counter()
|
173
|
+
insert_to_access(path_access,df,'testtable2',dtypes)
|
174
|
+
end_time = time.perf_counter()
|
175
|
+
elapsed_time = end_time - start_time
|
176
|
+
print(elapsed_time)
|
177
|
+
|
178
|
+
|
179
|
+
start_time = time.perf_counter()
|
180
|
+
insert_to_access2(path_access,df,'testtable3',dtypes)
|
181
|
+
end_time = time.perf_counter()
|
182
|
+
elapsed_time = end_time - start_time
|
183
|
+
print(elapsed_time)
|
184
|
+
|
185
|
+
```
|
186
|
+
結果は
|
187
|
+
1が22秒
|
188
|
+
2が35秒
|
189
|
+
3が6秒
|
190
|
+
でした。
|
191
|
+
|
192
|
+
やはり、リンク先の内容の通りということなのでしょうか。
|
193
|
+
データの量を増やしてどう変わるかについては、また検証してみます。
|