Curso de Programación en Python/MySQL-4
Ir a la navegación
Ir a la búsqueda
MySQL-4.py
1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3
4 import mysql.connector
5 from mysql.connector import errorcode
6
7 config = {
8 'user': 'PythonClase',
9 'password': 'Py800se',
10 'host': '127.0.0.1',
11 'database': 'PythonClase',
12 'raise_on_warnings': True,
13 'unix_socket': '/var/lib/mysql/mysql.sock'
14 }
15
16 try:
17 Conn = mysql.connector.connect(**config)
18 except mysql.connector.Error as err:
19 if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
20 print( "UsuarioNombre o Contraseña incorrecto" )
21 elif err.errno == errorcode.ER_BAD_DB_ERROR:
22 print( "Base de Datos no existe" )
23 else:
24 print( err )
25
26 Cursor = Conn.cursor()
27
28 Query = "INSERT INTO TablaDePrueba values ( NULL, 'Valor 1' )";
29
30 Cursor.execute( Query )
31
32 Conn.commit()
33
34 Query = "INSERT INTO TablaDePrueba ( CampoDePueba ) values ( 'Valor 2' )";
35
36 Cursor.execute( Query )
37
38 Conn.commit()
39
40 Conn.close()
41
42 print( "Mira en la TablaDePrueba a ver los registros nuevos" )
Resultado
[rrc@Pridd PythonClase]$ mysql -u PythonClase -pPy800se Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 27 Server version: 10.0.22-MariaDB Mageia MariaDB Server Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> use PythonClase Database changed MariaDB [PythonClase]> select * from TablaDePrueba; +----+--------------+ | id | CampoDePueba | +----+--------------+ | 1 | Valor 1 | | 2 | Valor 2 | +----+--------------+ 1 row in set (0.00 sec) MariaDB [PythonClase]>