Cara menggunakan python mysql client

The connect() constructor creates a connection to the MySQL server and returns a MySQLConnection object.

The following example shows how to connect to the MySQL server:

import mysql.connector

cnx = mysql.connector.connect(user='scott', password='password',
                              host='127.0.0.1',
                              database='employees')
cnx.close()

Section 7.1, “Connector/Python Connection Arguments” describes the permitted connection arguments.

It is also possible to create connection objects using the connection.MySQLConnection() class:

from mysql.connector import (connection)

cnx = connection.MySQLConnection(user='scott', password='password',
                                 host='127.0.0.1',
                                 database='employees')
cnx.close()

Both forms (either using the connect() constructor or the class directly) are valid and functionally equal, but using connect() is preferred and used by most examples in this manual.

To handle connection errors, use the try statement and catch all errors using the errors.Error exception:

import mysql.connector
from mysql.connector import errorcode

try:
  cnx = mysql.connector.connect(user='scott',
                                database='employ')
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cnx.close()

Defining connection arguments in a dictionary and using the ** operator is another option:

import mysql.connector

config = {
  'user': 'scott',
  'password': 'password',
  'host': '127.0.0.1',
  'database': 'employees',
  'raise_on_warnings': True
}

cnx = mysql.connector.connect(**config)

cnx.close()

Using the Connector/Python Python or C Extension

Connector/Python offers two implementations: a pure Python interface and a C extension that uses the MySQL C client library (see Chapter 8, The Connector/Python C Extension). This can be configured at runtime using the use_pure connection argument. It defaults to False as of MySQL 8, meaning the C extension is used. If the C extension is not available on the system then use_pure defaults to True. Setting use_pure=False causes the connection to use the C Extension if your Connector/Python installation includes it, while use_pure=True to False means the Python implementation is used if available.

Note

The use_pure option and C extension were added in Connector/Python 2.1.1.

The following example shows how to set use_pure to False.

import mysql.connector

cnx = mysql.connector.connect(user='scott', password='password',
                              host='127.0.0.1',
                              database='employees',
                              use_pure=False)
cnx.close()

It is also possible to use the C Extension directly by importing the _mysql_connector module rather than the mysql.connector module. For more information, see Section 8.2, “The _mysql_connector C Extension Module”.

Saya ingin menjauh dari PHP sedikit dan belajar Python. Untuk melakukan pengembangan web dengan Python saya akan membutuhkan kerangka kerja untuk membantu dengan templating dan hal-hal lain.

Saya memiliki server non-produksi yang saya gunakan untuk menguji semua hal pengembangan web. Ini adalah tumpukan LAM Debian 7.1 yang menjalankan MariaDB bukan paket MySQL-server umum.

Kemarin saya menginstal Django dan membuat proyek pertama saya bernama firstweb . Saya belum mengubah pengaturan apa pun.

Ini adalah kebingungan besar pertama saya. Dalam tutorial saya mengikuti orang itu menginstal Django, memulai proyek pertamanya, me-restart Apache, dan Django baru bekerja sejak saat itu. Dia pergi ke browser-nya dan pergi ke halaman default Django tanpa masalah.

Namun saya, saya harus cd ke folder web pertama saya dan jalankan

python manage.py runserver myip:port

Dan itu berhasil. Tidak masalah. Tapi saya bertanya-tanya apakah itu seharusnya bekerja seperti ini, dan apakah ini akan menyebabkan masalah di telepon?

Saya pertanyaan kedua adalah bahwa saya ingin mengaturnya sehingga menggunakan basis data MySQL saya. Saya masuk ke settings.py saya di bawah/firstweb/firstweb dan saya melihat ENGINE dan NAME tapi saya tidak yakin apa yang harus dimasukkan di sini.

Dan kemudian di area PENGGUNA, SANDI, dan Host apakah ini basis data dan kredensial saya? Jika saya menggunakan localhost dapatkah saya menaruh localhost di area Host ?

dukungan MySQL mudah untuk ditambahkan. Dalam kamus DATABASES Anda, Anda akan memiliki entri seperti ini:

DATABASES = {
    'default': {
        'ENGINE': 'Django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'Host': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

Anda juga memiliki opsi untuk menggunakan MySQL file opsi , mulai Django 1.7. Anda dapat melakukannya dengan mengatur array DATABASES Anda seperti:

DATABASES = {
    'default': {
        'ENGINE': 'Django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

Anda juga perlu membuat file /path/to/my.cnf dengan pengaturan serupa dari atas

[client]
database = DB_NAME
Host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

Dengan metode baru menghubungkan ini di Django 1.7, penting untuk mengetahui urutan koneksi dibuat:

1. OPTIONS.
2. NAME, USER, PASSWORD, Host, PORT
3. MySQL option files.

Dengan kata lain, jika Anda menetapkan nama basis data dalam PILIHAN, ini akan lebih diutamakan daripada NAMA, yang akan menimpa apa pun dalam file opsi MySQL.


Jika Anda hanya menguji aplikasi Anda di mesin lokal Anda, Anda dapat menggunakannya

python manage.py runserver

Menambahkan argumen ip:port memungkinkan mesin selain milik Anda untuk mengakses aplikasi pengembangan Anda. Setelah Anda siap untuk menyebarkan aplikasi Anda, saya sarankan untuk melihat bab pada Menyebarkan Django pada djangobook

Kumpulan karakter default Mysql sering tidak utf-8, karena itu pastikan untuk membuat database Anda menggunakan sql ini:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

Jika Anda menggunakan konektor MySQL Oracle baris ENGINE Anda akan terlihat seperti ini:

'ENGINE': 'mysql.connector.Django',

Perhatikan bahwa Anda harus menginstal mysql terlebih dahulu pada OS Anda.

brew install mysql (MacOS)

Juga, paket klien mysql telah berubah untuk python 3 (MySQL-Client hanya berfungsi untuk python 2)

pip3 install mysqlclient

Untuk yang pertama silakan jalankan perintah di bawah ini untuk menginstal dependensi python jika tidak, perintah python runserver akan melempar kesalahan.

Sudo apt-get install libmysqlclient-dev
Sudo pip install MySQL-python

Kemudian konfigurasikan file settings.py seperti yang didefinisikan oleh #Andy dan terakhir jalankan:

python manage.py runserver

Selamat bersenang-senang..!!

Seperti semua yang dikatakan di atas, Anda dapat dengan mudah menginstal xampp terlebih dahulu dari https://www.apachefriends.org/download.html Kemudian ikuti petunjuknya sebagai:

  1. Instal dan jalankan xampp dari http://www.unixmen.com/install-xampp-stack-ubuntu-14-04/ , kemudian mulai Apache Web Server dan Database MySQL dari GUI.
  2. Anda dapat mengkonfigurasi server web seperti yang Anda inginkan tetapi secara default server web ada di http://localhost:80 dan database di port 3306, dan PhpMyadmin di http://localhost/phpmyadmin/
  3. Dari sini Anda dapat melihat database Anda dan mengaksesnya menggunakan GUI yang sangat ramah.
  4. Buat database apa saja yang ingin Anda gunakan pada Proyek Django Anda.
  5. Edit file settings.py Anda seperti:

    DATABASES = {
    'default': {
        'ENGINE': 'Django.db.backends.mysql',
        'NAME': 'DB_NAME',
        'Host': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '',
    }}
    
  6. Instal paket-paket berikut di virtualenv (jika Anda menggunakan Django di virtualenv, yang lebih disukai):

    Sudo apt-get install libmysqlclient-dev

    pip instal MySQL-python

  7. Itu dia!! Anda telah mengkonfigurasi Django dengan MySQL dengan cara yang sangat mudah.

  8. Sekarang jalankan proyek Django Anda:

    migrasi python manage.py

    python manage.py runserver

Jika Anda menggunakan python3.x maka Jalankan di bawah perintah

pip install mysqlclient

Kemudian ubah setting.py suka

DATABASES = {
'default': {
    'ENGINE': 'Django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',
  }
  }

Sebenarnya, ada banyak masalah dengan lingkungan yang berbeda, versi python, dan sebagainya. Anda mungkin juga perlu menginstal file python dev, jadi untuk 'brute-force' instalasi saya akan menjalankan semua ini:

Sudo apt-get install python-dev python3-dev
Sudo apt-get install libmysqlclient-dev
pip install MySQL-python
pip install pymysql
pip install mysqlclient

Anda harus bersikap baik dengan jawaban yang diterima. Dan dapat menghapus paket yang tidak perlu jika itu penting bagi Anda.

Jalankan perintah ini

Sudo apt-get install python-dev python3-dev

Sudo apt-get install libmysqlclient-dev

pip instal MySQL-python

pip instal pymysql

pip instal mysqlclient

Kemudian konfigurasikan settings.py like

DATABASES = {
    'default': {
        'ENGINE': 'Django.db.backends.mysql',
        'NAME': 'Django_db',
        'Host': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123456',
    }
}

Nikmati koneksi mysql

Jawaban Andy membantu tetapi jika Anda memiliki kepedulian untuk mengekspos kata sandi database Anda dalam pengaturan Django Anda, saya sarankan untuk mengikuti konfigurasi resmi Django pada koneksi mysql: https://docs.djangoproject.com/en/1.7/ref/databases /

Dikutip di sini sebagai:

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'Django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}


# my.cnf
[client]
database = NAME
user = USER
password = PASSWORD
default-character-set = utf8

Untuk mengganti 'Host': '127.0.0.1' di pengaturan, cukup tambahkan di my.cnf:

# my.cnf
[client]
database = NAME
Host = Host NAME or IP
user = USER
password = PASSWORD
default-character-set = utf8

OPSI lain yang berguna, adalah untuk mengatur mesin penyimpanan Anda untuk Django, Anda mungkin menginginkannya di setting.py Anda:

'OPTIONS': {
   'init_command': 'SET storage_engine=INNODB',
}

settings.py

DATABASES = {
'default': {
    'ENGINE': 'Django.db.backends.mysql',
    'NAME': 'Django',
    'USER': 'root',
    'PASSWORD': '*****',
    'Host': '***.***.***.***',
    'PORT': '3306',
    'OPTIONS': {
        'autocommit': True,
    },
}

}

kemudian:

python manage.py migrate

jika sukses akan menghasilkan tabel tesis:

auth_group
auth_group_permissions
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions
Django_admin_log
Django_content_type
Django_migrations
Django_session

dan kamu akan dapat menggunakan mysql.

ini adalah contoh showcase, uji pada Django versi 1.11.5: Django-pool-showcase

Ikuti langkah-langkah yang diberikan untuk menyiapkannya menggunakan database MySQL:

1) Install MySQL Database Connector :

    Sudo apt-get install libmysqlclient-dev

2) Install the mysqlclient library :

    pip install mysqlclient

3) Install MySQL server, with the following command :

    Sudo apt-get install mysql-server

4) Create the Database :

    i) Verify that the MySQL service is running:

        systemctl status mysql.service

    ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :  

        mysql -u db_user -p


    iii) CREATE DATABASE db_name;

    iv) Exit MySQL server, press CTRL + D.

5) Add the MySQL Database Connection to your Application:

    i) Navigate to the settings.py file and replace the current DATABASES lines with the following:

        # Database
        # https://docs.djangoproject.com/en/2.0/ref/settings/#databases

        DATABASES = {
            'default': {
                'ENGINE': 'Django.db.backends.mysql',
                'OPTIONS': {
                    'read_default_file': '/etc/mysql/my.cnf',
                },
            }
        }
        ...

    ii) Next, let’s edit the config file so that it has your MySQL credentials. Use vi as Sudo to edit the file and add the following information:

        Sudo vi /etc/mysql/my.cnf

        database = db_name
        user = db_user
        password = db_password
        default-character-set = utf8

6) Once the file has been edited, we need to restart MySQL for the changes to take effect :

    systemctl daemon-reload

    systemctl restart mysql

7) Test MySQL Connection to Application:

    python manage.py runserver your-server-ip:8000

Anda harus membuat database MySQL terlebih dahulu. Lalu buka file settings.py dan edit kamus 'DATABASES' dengan kredensial MySQL Anda:

DATABASES = {
 'default': {
 'ENGINE': 'Django.db.backends.mysql',
 'NAME': 'YOUR_DATABASE_NAME',
 'USER': 'YOUR_MYSQL_USER',
 'PASSWORD': 'YOUR_MYSQL_PASS',
 'Host': 'localhost',   # Or an IP that your DB is hosted on
 'PORT': '3306',
 }
}

Berikut ini adalah panduan instalasi lengkap untuk mengatur Django untuk menggunakan MySQL pada virtualenv:

http://codex.themedelta.com/how-to-install-Django-with-mysql-in-a-virtualenv-on-linux/