Curso de Programación en Python/MySQL-4

De WikiCabal
Saltar a: navegación, buscar

MySQL-4.py

#!/usr/bin/python3
#-*-coding: utf-8 -*-

import mysql.connector
from mysql.connector import errorcode

config = {
  'user': 'PythonClase',
  'password': 'Py800se',
  'host': '127.0.0.1',
  'database': 'PythonClase',
  'raise_on_warnings': True,
  'unix_socket': '/var/lib/mysql/mysql.sock'
}

try:
  Conn = mysql.connector.connect(**config)
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print( "UsuarioNombre o Contraseña incorrecto" )
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print( "Base de Datos no existe" )
  else:
    print( err )

Cursor = Conn.cursor()   

Query = "INSERT INTO TablaDePrueba values ( NULL, 'Valor 1' )";

Cursor.execute( Query )

Conn.commit()

Query = "INSERT INTO TablaDePrueba ( CampoDePueba ) values ( 'Valor 2' )";

Cursor.execute( Query )

Conn.commit()

Conn.close()

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]>