bbdd-utils 0.3.15__py3-none-any.whl → 0.3.16__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bbdd_utils/functions.py +52 -0
- bbdd_utils/utils.py +22 -18
- {bbdd_utils-0.3.15.dist-info → bbdd_utils-0.3.16.dist-info}/METADATA +1 -1
- bbdd_utils-0.3.16.dist-info/RECORD +8 -0
- bbdd_utils-0.3.15.dist-info/RECORD +0 -7
- {bbdd_utils-0.3.15.dist-info → bbdd_utils-0.3.16.dist-info}/WHEEL +0 -0
- {bbdd_utils-0.3.15.dist-info → bbdd_utils-0.3.16.dist-info}/licenses/LICENSE +0 -0
- {bbdd_utils-0.3.15.dist-info → bbdd_utils-0.3.16.dist-info}/top_level.txt +0 -0
bbdd_utils/functions.py
ADDED
@@ -0,0 +1,52 @@
|
|
1
|
+
def dict_list_to_table(dict_list):
|
2
|
+
# Si la lista está vacía, devolver una lista vacía y None como encabezados
|
3
|
+
if not dict_list:
|
4
|
+
return None, []
|
5
|
+
|
6
|
+
# Obtener las claves del primer diccionario para usarlas como encabezados
|
7
|
+
columnas = list(dict_list[0].keys())
|
8
|
+
|
9
|
+
# Crear la lista para los datos (sin incluir encabezados)
|
10
|
+
data = []
|
11
|
+
|
12
|
+
# Agregar cada fila de valores
|
13
|
+
for item in dict_list:
|
14
|
+
# Extraer los valores en el mismo orden que los encabezados
|
15
|
+
row = [item.get(header, '') for header in columnas]
|
16
|
+
data.append(row)
|
17
|
+
|
18
|
+
return data, columnas
|
19
|
+
|
20
|
+
def exists_table(conn, table_name):
|
21
|
+
cursor = conn.cursor()
|
22
|
+
cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';")
|
23
|
+
result = cursor.fetchone()
|
24
|
+
return result is not None
|
25
|
+
|
26
|
+
def create_table(conn, table_name, columnas):
|
27
|
+
cursor = conn.cursor()
|
28
|
+
# Crear la tabla con las columnas especificadas
|
29
|
+
cursor.execute(f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(columnas)});")
|
30
|
+
conn.commit()
|
31
|
+
print(f"Tabla '{table_name}' creada exitosamente.")
|
32
|
+
|
33
|
+
def insertar_datos(conn, tabla, data, columnas):
|
34
|
+
# Crear el cursor
|
35
|
+
cursor = conn.cursor()
|
36
|
+
|
37
|
+
# Construir la sentencia SQL apropiada
|
38
|
+
nombres_columnas = ", ".join([f'"{col}"' for col in columnas])
|
39
|
+
marcadores = ", ".join(["?" for _ in columnas])
|
40
|
+
|
41
|
+
sql = f"INSERT INTO {tabla} ({nombres_columnas}) VALUES ({marcadores})"
|
42
|
+
|
43
|
+
# Insertar cada fila de datos
|
44
|
+
for fila in data:
|
45
|
+
try:
|
46
|
+
cursor.execute(sql, fila)
|
47
|
+
except Exception as e:
|
48
|
+
print(f"Error al insertar fila {fila}: {e}")
|
49
|
+
|
50
|
+
# Confirmar los cambios
|
51
|
+
conexion.commit()
|
52
|
+
print(f"Se insertaron {len(filas)} registros en la tabla {tabla}")
|
bbdd_utils/utils.py
CHANGED
@@ -1,3 +1,4 @@
|
|
1
|
+
|
1
2
|
def saludar(nombre):
|
2
3
|
return f"Hola, {nombre}! Esta es tu librería personalizada."
|
3
4
|
|
@@ -32,7 +33,7 @@ def Conector_bbdd(tipo='sqlite', nombre='mi_base_de_datos', host='localhost', pu
|
|
32
33
|
# Crear la base de datos
|
33
34
|
cursor = conn.cursor()
|
34
35
|
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {nombre}")
|
35
|
-
print(f"Base de datos
|
36
|
+
print(f"Base de datos My sql '{nombre}' creada exitosamente.")
|
36
37
|
return conn
|
37
38
|
|
38
39
|
elif tipo == 'mongodb':
|
@@ -43,7 +44,7 @@ def Conector_bbdd(tipo='sqlite', nombre='mi_base_de_datos', host='localhost', pu
|
|
43
44
|
port=puerto,
|
44
45
|
username=usuario,
|
45
46
|
password=password)
|
46
|
-
print(
|
47
|
+
print("Conectado a MongoDB")
|
47
48
|
return cliente[nombre]
|
48
49
|
|
49
50
|
else:
|
@@ -63,30 +64,33 @@ def Cerrar_conexion(conn):
|
|
63
64
|
conn.close()
|
64
65
|
|
65
66
|
def Insert(conn, tabla, data):
|
66
|
-
|
67
|
+
#importacion de librerias
|
67
68
|
import sqlite3
|
68
69
|
import mysql.connector
|
69
70
|
from pymongo.database import Database
|
71
|
+
from functions import dict_list_to_table, exists_table, create_table, insertar_datos
|
72
|
+
|
70
73
|
|
71
74
|
############# SQLite ################
|
72
75
|
if isinstance(conn, sqlite3.Connection):
|
73
|
-
print("Conexión exitosa a la base de datos SQL.")
|
74
76
|
cursor = conn.cursor()
|
75
|
-
# Crear la tabla dinámicamente si no existe
|
76
|
-
columnas_definicion = ", ".join([f"{col} TEXT" for col in columnas])
|
77
|
-
cursor.execute(f"""
|
78
|
-
CREATE TABLE IF NOT EXISTS {tabla} (
|
79
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
80
|
-
{columnas_definicion}
|
81
|
-
)
|
82
|
-
""")
|
83
|
-
print(f"Tabla '{tabla}' verificada o creada exitosamente.")
|
84
77
|
|
85
|
-
|
86
|
-
|
87
|
-
|
88
|
-
|
89
|
-
|
78
|
+
# Verifica el tipo de base de datos con la que estamos trabajando
|
79
|
+
if isinstance(data, dict):
|
80
|
+
# Si es una lista, convertimos a tabla
|
81
|
+
dict_list_to_table(data)
|
82
|
+
|
83
|
+
# verificar si la tabla existe
|
84
|
+
if exists_table(conn, tabla):
|
85
|
+
print(f"La tabla '{tabla}' ya existe.")
|
86
|
+
# Si la tabla existe, puedes insertar datos o realizar otras operaciones
|
87
|
+
|
88
|
+
else:
|
89
|
+
create_table(conn, tabla, data)
|
90
|
+
|
91
|
+
# Inserta datos en la tabla '{tabla}'
|
92
|
+
insertar_datos(conn, tabla, data, columnas)
|
93
|
+
|
90
94
|
|
91
95
|
# Consulta los datos insertados
|
92
96
|
cursor.execute("SELECT * FROM {tabla}")
|
@@ -0,0 +1,8 @@
|
|
1
|
+
bbdd_utils/__init__.py,sha256=mjRX7GqWkOJq66KqghZ4MZE0Aai6R89LPeu1mjq4lD4,121
|
2
|
+
bbdd_utils/functions.py,sha256=fo4pE9HsJ4AMYTmJ0itPAi9-gIvoh82H0qID198AL6A,1862
|
3
|
+
bbdd_utils/utils.py,sha256=wNE2IlHJXEidGdoexURDcjG92B-KYFUDGvIE_b2xp0c,5123
|
4
|
+
bbdd_utils-0.3.16.dist-info/licenses/LICENSE,sha256=D4uqg6QX0fapLNcdUznOuGaRIUPnypOdeE2zIyYq7xY,217
|
5
|
+
bbdd_utils-0.3.16.dist-info/METADATA,sha256=l3FFSYCLwSkt1ewxrwxFQ28dJSwuW1khpIoPQFPED2s,694
|
6
|
+
bbdd_utils-0.3.16.dist-info/WHEEL,sha256=DnLRTWE75wApRYVsjgc6wsVswC54sMSJhAEd4xhDpBk,91
|
7
|
+
bbdd_utils-0.3.16.dist-info/top_level.txt,sha256=bBGkVkxnOw7tZ2zRcyCM3lgVgYo1hFbcmwkGdKAj9Gk,11
|
8
|
+
bbdd_utils-0.3.16.dist-info/RECORD,,
|
@@ -1,7 +0,0 @@
|
|
1
|
-
bbdd_utils/__init__.py,sha256=mjRX7GqWkOJq66KqghZ4MZE0Aai6R89LPeu1mjq4lD4,121
|
2
|
-
bbdd_utils/utils.py,sha256=jNlSRZDS-Gtu4bDIeAA-U4AJxpnPIr6fGBT8PYSgwlg,5242
|
3
|
-
bbdd_utils-0.3.15.dist-info/licenses/LICENSE,sha256=D4uqg6QX0fapLNcdUznOuGaRIUPnypOdeE2zIyYq7xY,217
|
4
|
-
bbdd_utils-0.3.15.dist-info/METADATA,sha256=xOKF55KUzE2easD8nhun-58cW65O1KdLGYu41O7OmXY,694
|
5
|
-
bbdd_utils-0.3.15.dist-info/WHEEL,sha256=DnLRTWE75wApRYVsjgc6wsVswC54sMSJhAEd4xhDpBk,91
|
6
|
-
bbdd_utils-0.3.15.dist-info/top_level.txt,sha256=bBGkVkxnOw7tZ2zRcyCM3lgVgYo1hFbcmwkGdKAj9Gk,11
|
7
|
-
bbdd_utils-0.3.15.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|