У меня всего два вопроса:
Я пытался создать sh простой файл Excel на sql сервере data-base
и создайте базу данных с python, используя следующие библиотеки
- pandas
- os
- sqlalchemy
Как сейчас У меня есть простой excel
файл, содержащий 2 столбца, который мне нужен теперь, когда я перемещаю данные из файла Excel в базу данных, объединяю функцию конкатенации и создаю столбец в таблице в качестве функции конкатенации, как показано ниже:
hua_gsm_rel_key_df = hua_gsm_rel_df['Source Cell Name'].map(str) + '_' + hua_gsm_rel_df['Neighbor Cell Name'].map(str)
поскольку это мой полный код:
import pyodbc
import pandas as pd
import os
import sqlalchemy as db
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Date, Float
import datetime as dt
#Create a ditionary for excel file
hua_gsm_relations_col_dict = {
'source_cell_name': 'Source Cell Name',
'neighbor_cell_name': 'Neighbor Cell Name',
}
#table name
HUA_GSM_2G_RELATIONS = 'g2g_ncell'
#Create a list for hua_gsm_relations_cols and put the dictionary in the list
hua_gsm_relations_cols = list(hua_gsm_relations_col_dict.keys())
# connect db
engine = create_engine('mssql+pyodbc://WINKPN-3B5JTT2\SMARTRNO_EXPRESS/myDB?driver=SQL+Server+Native+Client+11.0')
connection = engine.connect()
hua_gsm_relations_cols_meta = MetaData()
hua_gsm_relations = Table(
HUA_GSM_2G_RELATIONS, hua_gsm_relations_cols_meta,
Column('id', Integer, primary_key=True),
Column(hua_gsm_relations_cols[0], Integer),
Column(hua_gsm_relations_cols[1], Integer),
)
if engine.dialect.has_table(engine, HUA_GSM_2G_RELATIONS):
hua_gsm_relations.drop(engine)
hua_gsm_relations_cols_meta.create_all(engine)
hua_gsm_rel_excel = '2G Radio Network Planning Data Template.xlsm'
hua_gsm_rel_df = pd.read_excel(os.path.join(os.path.dirname(__file__), hua_gsm_rel_excel), sheet_name='G2GNCELL', dtype={
hua_gsm_relations_col_dict[hua_gsm_relations_cols[0]]: int,
hua_gsm_relations_col_dict[hua_gsm_relations_cols[1]]: str,
}, header=1)
hua_gsm_rel_df['Neighbor Cell Name'].replace(regex=True,inplace=True,to_replace=r'\D',value=r'')
hua_gsm_rel_key_df = hua_gsm_rel_df['Source Cell Name'].map(str) + '_' + hua_gsm_rel_df['Neighbor Cell Name'].map(str)
hua_gsm_relations_table_query = db.insert(hua_gsm_relations)
hua_gsm_relations_values_list = []
hua_gsm_relations_hua_gsm_relations_row_count = 1
for i in hua_gsm_rel_df.index:
hua_gsm_relations_row = hua_gsm_rel_df.loc[i]
hua_gsm_rel_df_record = {'id': hua_gsm_relations_hua_gsm_relations_row_count}
for col in hua_gsm_relations_col_dict.keys():
if col == hua_gsm_relations_cols[0]:
hua_gsm_rel_df_record[col] = int(hua_gsm_relations_row[hua_gsm_relations_col_dict[col]])
else:
hua_gsm_rel_df_record[col] = hua_gsm_relations_row[hua_gsm_relations_col_dict[col]]
hua_gsm_relations_values_list.append(hua_gsm_rel_df_record)
hua_gsm_relations_hua_gsm_relations_row_count += 1
ResultProxy = engine.execute(hua_gsm_relations_table_query, hua_gsm_relations_values_list)
connection.close()
engine.dispose()
Теперь мне нужно создать еще один столбец с именем key
, используя этот concatenation
в базе данных, которую он показывает за двумя столбцами, как показано на рисунке ниже
Таблица в базе данных
- Теперь второй вопрос, как лучше всего извлечь sh данные из разных файлов Excel и создать таблицу с ними в базе данных, используя это код без создания этого кода для каждого файла Excel.
lik В приведенном ниже коде я хочу уменьшить его, который работает для нескольких баз данных:
import pyodbc
import pandas as pd
import os
import sqlalchemy as db
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Date, Float
import datetime as dt
#Create a ditionary for excel file
hua_gsm_relations_col_dict = {
'source_cell_name': 'Source Cell Name',
'neighbor_cell_name': 'Neighbor Cell Name',
}
#table name
HUA_GSM_2G_RELATIONS = 'g2g_ncell'
# 3G Radio Network Planning Data Template(Needed Columns)-INTRAFREQNCELL
hua_umts_intra_relations_col_dict = {
'cell_name': 'Cell Name',
'n_cell_name': 'Neighboring Cell Name',
}
HUA_3G_RELATIONS_INTRAFREQNCELL = 'intrafreq_cell'
#Create a list for hua_gsm_relations_cols and put the dictionary in the list
hua_gsm_relations_cols = list(hua_gsm_relations_col_dict.keys())
#Create a list for hua_gsm_relations_cols and put the dictionary in the list
hua_umts_intra_relations_cols = list(hua_umts_intra_relations_col_dict.keys())
# connect db
engine = create_engine('mssql+pyodbc://xxxxxxxx\SMARTRNO_EXPRESS/myDB?driver=SQL+Server+Native+Client+11.0')
connection = engine.connect()
hua_gsm_relations_cols_meta = MetaData()
hua_gsm_relations = Table(
HUA_GSM_2G_RELATIONS, hua_gsm_relations_cols_meta,
Column('id', Integer, primary_key=True),
Column(hua_gsm_relations_cols[0], Integer),
Column(hua_gsm_relations_cols[1], Integer),
)
hua_umts_intra_relations_cols_meta = MetaData()
hua_umts_intra_relations = Table(
HUA_3G_RELATIONS_INTRAFREQNCELL, hua_umts_intra_relations_cols_meta,
Column('id', Integer, primary_key=True),
Column(hua_umts_intra_relations_cols[0], Integer),
Column(hua_umts_intra_relations_cols[1], Integer),
)
if engine.dialect.has_table(engine, HUA_GSM_2G_RELATIONS):
hua_gsm_relations.drop(engine)
hua_gsm_relations_cols_meta.create_all(engine)
if engine.dialect.has_table(engine, HUA_3G_RELATIONS_INTRAFREQNCELL):
hua_umts_intra_relations.drop(engine)
hua_umts_intra_relations_cols_meta.create_all(engine)
hua_gsm_rel_excel = '2G Radio Network Planning Data Template.xlsm'
hua_umts_intra_rel_excel = '3G Radio Network Planning Data Template.xlsm'
hua_gsm_rel_df = pd.read_excel(os.path.join(os.path.dirname(__file__), hua_gsm_rel_excel), sheet_name='G2GNCELL', dtype={
hua_gsm_relations_col_dict[hua_gsm_relations_cols[0]]: int,
hua_gsm_relations_col_dict[hua_gsm_relations_cols[1]]: str,
}, header=1)
hua_umts_intra_rel_df = pd.read_excel(os.path.join(os.path.dirname(__file__), hua_umts_intra_rel_excel), sheet_name='INTRAFREQNCELL', dtype={
hua_umts_intra_relations_col_dict[hua_umts_intra_relations_cols[0]]: int,
hua_umts_intra_relations_col_dict[hua_umts_intra_relations_cols[1]]: str,
}, header=1)
hua_gsm_rel_df['Neighbor Cell Name'].replace(regex=True,inplace=True,to_replace=r'\D',value=r'')
hua_umts_intra_rel_df['Neighboring Cell Name'].replace(regex=True,inplace=True,to_replace=r'\D',value=r'')
hua_gsm_rel_key_df = hua_gsm_rel_df['Source Cell Name'].map(str) + '_' + hua_gsm_rel_df['Neighbor Cell Name'].map(str)
hua_umts_intra_rel_key_df = hua_umts_intra_rel_df['Cell Name'].map(str) + '_' + hua_umts_intra_rel_df['Neighboring Cell Name'].map(str)
hua_gsm_relations_table_query = db.insert(hua_gsm_relations)
hua_gsm_relations_values_list = []
hua_gsm_relations_row_count = 1
for i in hua_gsm_rel_df.index:
hua_gsm_relations_row = hua_gsm_rel_df.loc[i]
hua_gsm_rel_df_record = {'id': hua_gsm_relations_row_count}
for col in hua_gsm_relations_col_dict.keys():
if col == hua_gsm_relations_cols[0]:
hua_gsm_rel_df_record[col] = int(hua_gsm_relations_row[hua_gsm_relations_col_dict[col]])
else:
hua_gsm_rel_df_record[col] = hua_gsm_relations_row[hua_gsm_relations_col_dict[col]]
hua_gsm_relations_values_list.append(hua_gsm_rel_df_record)
hua_gsm_relations_row_count += 1
ResultProxy_hua_gsm_relations = engine.execute(hua_gsm_relations_table_query, hua_gsm_relations_values_list)
hua_umts_intra_relations_table_query = db.insert(hua_umts_intra_relations)
hua_umts_intra_relations_values_list = []
hua_umts_intra_relations_row_count = 1
for i in hua_umts_intra_rel_df.index:
hua_umts_intra_relations_row = hua_umts_intra_rel_df.loc[i]
hua_umts_inta_rel_df_record = {'id': hua_umts_intra_relations_row_count}
for col in hua_umts_intra_relations_col_dict.keys():
if col == hua_umts_intra_relations_cols[0]:
hua_umts_inta_rel_df_record[col] = int(hua_umts_intra_relations_row[hua_umts_intra_relations_col_dict[col]])
else:
hua_umts_inta_rel_df_record[col] = hua_umts_intra_relations_row[hua_umts_intra_relations_col_dict[col]]
hua_umts_intra_relations_values_list.append(hua_umts_inta_rel_df_record)
hua_umts_intra_relations_row_count += 1
ResultProxy_hua_umts_intra_relations = engine.execute(hua_umts_intra_relations_table_query, hua_umts_intra_relations_values_list)
connection.close()
engine.dispose()
Прошу прощения за плохой Engli sh, но я попытался объяснить как можно больше:).