Basic Usage

Once you have umysql3 installed, lets test if the installation is successful.

python3.4 -c "import umysql3"

If the above statement does not throw any error then your installation is working fine. Now we can jump on to the Hello World example.

Prerequisite:

MySql server connection settings like:

  • Hostname
  • Port
  • Database username and password
  • Database name

The example below does the following, and should give a basic understanding of the library usage:

  • Create a new table
  • Insert data into it
  • Fetch the data from the table and prints it

Example

import umysql3

DB_HOST = 'localhost'
DB_PORT = 3306
DB_USER = 'root'
DB_PASS = ''
DB_NAME = 'test'


def get_connection():
    connection = umysql3.Connection()
    connection.connect(DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME)

    return connection


def close_connection(connection):
    connection.close()


def insert_user(connection, name, age):

    INSERT_USER_QUERY="""
        INSERT INTO users(name, age) values('%s', %d);
    """ % (name, age)

    result_set = connection.query(INSERT_USER_QUERY)


def create_table_users(connection):

    CREATE_USERS_TABLE="""
        CREATE TABLE users(
            id INT(11) PRIMARY KEY AUTO_INCREMENT,
            name varchar(256),
            age INT
        );
    """

    result_set = connection.query(CREATE_USERS_TABLE)


def drop_table_users(connection):

    DROP_USERS_TABLE="""
        DROP TABLE users;
    """

    result_set = connection.query(DROP_USERS_TABLE)


def print_users(connection):

    ALL_USERS_QUERY="""
        SELECT id, name, age FROM users;
    """

    result_set = connection.query(ALL_USERS_QUERY)

    for row in result_set.rows:
        print("Found %s years old %s with id = %s" % (row[2], row[1], row[0]))


if __name__ == '__main__':
    c = get_connection()
    create_table_users(c)
    insert_user(c, "Barry Allen", 26)
    insert_user(c, "Zoom", 25)
    print_users(c)
    drop_table_users(c)
    close_connection(c)

results matching ""

    No results matching ""