Skip to content

Commit c74c93e

Browse files
committed
Initial commit
0 parents  commit c74c93e

13 files changed

+352
-0
lines changed

.gitattributes

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Auto detect text files and perform LF normalization
2+
* text=auto

.gitignore

+114
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
*.egg-info/
24+
.installed.cfg
25+
*.egg
26+
MANIFEST
27+
28+
# PyInstaller
29+
# Usually these files are written by a python script from a template
30+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
31+
*.manifest
32+
*.spec
33+
34+
# Installer logs
35+
pip-log.txt
36+
pip-delete-this-directory.txt
37+
38+
# Unit test / coverage reports
39+
htmlcov/
40+
.tox/
41+
.nox/
42+
.coverage
43+
.coverage.*
44+
.cache
45+
nosetests.xml
46+
coverage.xml
47+
*.cover
48+
.hypothesis/
49+
.pytest_cache/
50+
51+
# Translations
52+
*.mo
53+
*.pot
54+
55+
# Django stuff:
56+
*.log
57+
local_settings.py
58+
db.sqlite3
59+
60+
# Flask stuff:
61+
instance/
62+
.webassets-cache
63+
64+
# Scrapy stuff:
65+
.scrapy
66+
67+
# Sphinx documentation
68+
docs/_build/
69+
70+
# PyBuilder
71+
target/
72+
73+
# Jupyter Notebook
74+
.ipynb_checkpoints
75+
76+
# IPython
77+
profile_default/
78+
ipython_config.py
79+
80+
# pyenv
81+
.python-version
82+
83+
# celery beat schedule file
84+
celerybeat-schedule
85+
86+
# SageMath parsed files
87+
*.sage.py
88+
89+
# Environments
90+
.env
91+
.venv
92+
env/
93+
venv/
94+
ENV/
95+
env.bak/
96+
venv.bak/
97+
98+
# Spyder project settings
99+
.spyderproject
100+
.spyproject
101+
102+
# Rope project settings
103+
.ropeproject
104+
105+
# mkdocs documentation
106+
/site
107+
108+
# mypy
109+
.mypy_cache/
110+
.dmypy.json
111+
dmypy.json
112+
113+
# Pyre type checker
114+
.pyre/

LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2019 Luis Cabrera Benito
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# crud-sql-server-python

bd.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""
2+
Conexión a SQLServer con Python
3+
Ejemplo de CRUD evitando inyecciones SQL
4+
5+
@author parzibyte
6+
7+
Más tutoriales en:
8+
parzibyte.me/blog
9+
"""
10+
import pyodbc
11+
direccion_servidor = '127.0.0.1'
12+
nombre_bd = 'pruebas_parzibyte'
13+
nombre_usuario = 'usuario'
14+
password = 'hunter2'
15+
try:
16+
conexion = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' +
17+
direccion_servidor+';DATABASE='+nombre_bd+';UID='+nombre_usuario+';PWD=' + password)
18+
# OK! conexión exitosa
19+
except Exception as e:
20+
# Atrapar error
21+
print("Ocurrió un error al conectar a SQL Server: ", e)

consultar.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
Conexión a SQLServer con Python
3+
Ejemplo de CRUD evitando inyecciones SQL
4+
5+
@author parzibyte
6+
7+
Más tutoriales en:
8+
parzibyte.me/blog
9+
"""
10+
from bd import conexion
11+
12+
try:
13+
with conexion.cursor() as cursor:
14+
# En este caso no necesitamos limpiar ningún dato
15+
cursor.execute("SELECT id, titulo, anio FROM peliculas;")
16+
17+
# Con fetchall traemos todas las filas
18+
peliculas = cursor.fetchall()
19+
20+
# Recorrer e imprimir
21+
for pelicula in peliculas:
22+
print(pelicula)
23+
except Exception as e:
24+
print("Ocurrió un error al consultar: ", e)
25+
finally:
26+
conexion.close()

consultar_cursor.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
Conexión a SQLServer con Python
3+
Ejemplo de CRUD evitando inyecciones SQL
4+
5+
@author parzibyte
6+
7+
Más tutoriales en:
8+
parzibyte.me/blog
9+
"""
10+
from bd import conexion
11+
12+
try:
13+
with conexion.cursor() as cursor:
14+
# En este caso no necesitamos limpiar ningún dato
15+
cursor.execute("SELECT id, titulo, anio FROM peliculas;")
16+
# Hacer un while, mientras fetchone no regrese None
17+
pelicula = cursor.fetchone()
18+
while pelicula:
19+
print(pelicula)
20+
pelicula = cursor.fetchone()
21+
except Exception as e:
22+
print("Ocurrió un error al consultar: ", e)
23+
finally:
24+
conexion.close()

consultar_where.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
Conexión a SQLServer con Python
3+
Ejemplo de CRUD evitando inyecciones SQL
4+
5+
@author parzibyte
6+
7+
Más tutoriales en:
8+
parzibyte.me/blog
9+
"""
10+
from bd import conexion
11+
try:
12+
with conexion.cursor() as cursor:
13+
14+
consulta = "SELECT id, titulo, anio FROM peliculas WHERE anio > ?;"
15+
cursor.execute(consulta, (2000))
16+
17+
# Con fetchall traemos todas las filas
18+
peliculas = cursor.fetchall()
19+
20+
# Recorrer e imprimir
21+
for pelicula in peliculas:
22+
print(pelicula)
23+
except Exception as e:
24+
print("Ocurrió un error al consultar con where: ", e)
25+
finally:
26+
conexion.close()

consultar_where_like.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
Conexión a SQLServer con Python
3+
Ejemplo de CRUD evitando inyecciones SQL
4+
5+
@author parzibyte
6+
7+
Más tutoriales en:
8+
parzibyte.me/blog
9+
"""
10+
from bd import conexion
11+
try:
12+
with conexion.cursor() as cursor:
13+
consulta = "SELECT id, titulo, anio FROM peliculas WHERE titulo like ?;"
14+
# Para Avengers Endgame
15+
busqueda = "endg"
16+
cursor.execute(consulta, ("%" + busqueda + "%"))
17+
18+
# Con fetchall traemos todas las filas
19+
peliculas = cursor.fetchall()
20+
21+
# Recorrer e imprimir
22+
for pelicula in peliculas:
23+
print(pelicula)
24+
except Exception as e:
25+
print("Ocurrió un error al consultar con where: ", e)
26+
finally:
27+
conexion.close()

editar.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
Conexión a SQLServer con Python
3+
Ejemplo de CRUD evitando inyecciones SQL
4+
5+
@author parzibyte
6+
7+
Más tutoriales en:
8+
parzibyte.me/blog
9+
"""
10+
from bd import conexion
11+
try:
12+
with conexion.cursor() as cursor:
13+
14+
consulta = "UPDATE peliculas SET titulo = ? WHERE id = ?;"
15+
nuevo_titulo = "Ready Player One: comienza el juego"
16+
id_editar = 2
17+
cursor.execute(consulta, (nuevo_titulo, id_editar))
18+
19+
# No olvidemos hacer commit cuando hacemos un cambio a la BD
20+
conexion.commit()
21+
except Exception as e:
22+
print("Ocurrió un error al editar: ", e)
23+
finally:
24+
conexion.close()

eliminar.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
Conexión a SQLServer con Python
3+
Ejemplo de CRUD evitando inyecciones SQL
4+
5+
@author parzibyte
6+
7+
Más tutoriales en:
8+
parzibyte.me/blog
9+
"""
10+
from bd import conexion
11+
try:
12+
with conexion.cursor() as cursor:
13+
14+
consulta = "DELETE FROM peliculas WHERE anio < ?;"
15+
anio = 2000
16+
cursor.execute(consulta, (anio))
17+
18+
# No olvidemos hacer commit cuando hacemos un cambio a la BD
19+
conexion.commit()
20+
except Exception as e:
21+
print("Error eliminando: ", e)
22+
finally:
23+
conexion.close()

esquema.sql

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/*
2+
Conexión a SQLServer con Python
3+
Ejemplo de CRUD evitando inyecciones SQL
4+
5+
@author parzibyte
6+
7+
Más tutoriales en:
8+
parzibyte.me/blog
9+
*/
10+
CREATE TABLE IF NOT EXISTS peliculas(
11+
id bigint identity(1,1) primary key,
12+
titulo VARCHAR(255) NOT NULL,
13+
anio SMALLINT NOT NULL
14+
);

insertar.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Conexión a SQLServer con Python
3+
Ejemplo de CRUD evitando inyecciones SQL
4+
5+
@author parzibyte
6+
7+
Más tutoriales en:
8+
parzibyte.me/blog
9+
"""
10+
from bd import conexion
11+
try:
12+
with conexion.cursor() as cursor:
13+
consulta = "INSERT INTO peliculas(titulo, anio) VALUES (?, ?);"
14+
# Podemos llamar muchas veces a .execute con datos distintos
15+
cursor.execute(consulta, ("Volver al futuro 1", 1985))
16+
cursor.execute(consulta, ("Pulp Fiction", 1994))
17+
cursor.execute(consulta, ("It", 2017))
18+
cursor.execute(consulta, ("Ready Player One", 2018))
19+
cursor.execute(consulta, ("Spider-Man: un nuevo universo", 2018))
20+
cursor.execute(consulta, ("Avengers: Endgame", 2019))
21+
cursor.execute(consulta, ("John Wick 3: Parabellum", 2019))
22+
cursor.execute(consulta, ("Toy Story 4", 2019))
23+
cursor.execute(consulta, ("It 2", 2019))
24+
cursor.execute(consulta, ("Spider-Man: lejos de casa", 2019))
25+
26+
except Exception as e:
27+
print("Ocurrió un error al insertar: ", e)
28+
finally:
29+
conexion.close()

0 commit comments

Comments
 (0)