Přeskočit na obsah

Python/modul/mysql.connector

Z Wikiverzity

mysql.connector je Pythoní modul pro práci s databází MySQL

Mysql connector Python adhere to Python Database API Specification v2.0 (PEP 249)

It is written in pure Python and does not have any dependencies except for the Python Standard Library.

MySQL Connector Python does not support the old MySQL Server authentication methods, which means You need to use MySQL versions greater than 4.1.

Info

[editovat]

Externí odkazy

[editovat]

Tutoriál

[editovat]

Vytvoření databáze

[editovat]

Databázi pytest si zatím vytvoříme předem pomocí PHPMyAdmin nebo pomocí klienta mysql a v databázi si pak vytvoříme jednu tabulku seznam:

CREATE TABLE IF NOT EXISTS `seznam` (
  `id` int(11) NOT NULL,
  `name` varchar(10) COLLATE utf8_czech_ci DEFAULT NULL,
  `number` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;

INSERT INTO `seznam` (`id`, `name`, `number`) VALUES
(1, 'Adam', 111),
(2, 'Božena', 222),
(3, 'Cyril', 333),
(4, 'David', 444);

Připojení k databázi

[editovat]
#!/usr/bin/env python3

import mysql.connector
from mysql.connector import Error
 
 
def connect():
    """ Connect to MySQL database """
    try:
        conn = mysql.connector.connect(host='localhost',
                                       database='pytest',
                                       user='kychot',
                                       password='***********')
        if conn.is_connected():
            print('Connected to MySQL database')
        else:
            print('connection failed.')
 
    except Error as e:
        print(e)
 
    finally:
        conn.close()
 
if __name__ == '__main__':
    connect()

Výpis z databáze

[editovat]
#!/usr/bin/env python3

"""http://www.mysqltutorial.org/python-mysql/"""

from mysql.connector import connect, Error
 
def query_with_fetchall():
    try:
        conn = connect(host='localhost',
                       database='pytest',
                       user='kychot',
                       password='*************')
        if conn.is_connected():
            print('Connected to MySQL database')
        else:
            print('connection failed.')
 
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM seznam")
        rows = cursor.fetchall()
 
        print('Total Row(s):', cursor.rowcount)
        for row in rows:
            print(row)
 
    except Error as e:
        print(e)
 
    finally:
        cursor.close()
        conn.close()
  
if __name__ == '__main__':
    query_with_fetchall()

Výstupem bude:

Connected to MySQL database
Total Row(s): 4
(1, 'Adam', 111)
(2, 'Božena', 222)
(3, 'Cyril', 333)
(4, 'David', 444)