▲TOPへ戻る

【python】mysql-connector-pythonを使って、ロリポップのデータベースにMySqlで接続する

ロリポップ python データベース

接続前の準備

注意‼

ロリポップでPythonが使えますが, SSH接続ができるのは、スタンダード以上のプランだけです。 エコノミー、ライトプランはSSH接続できません。

SSH接続ができないと、必要なモジュールがインストールできません。

ロリポップ SSH

SSLでモジュールをダウンロード

Tera TermでSSH接続します。 python3 -m pip listで、リストの中に、mysql-connector-python がなければ、python3 -m pip install mysql-connector-pythonでインストールします。

ロリポップ tera term
<!--SSHでmysql-connector-pythonをインストール-->
python3 -m pip install mysql-connector-python

データベースに接続

ロリポップ!ユーザー専用ページにログインし、データベースを確認。

データベース
#!/usr/local/bin/python3.7

import mysql.connector
from mysql.connector import errorcode

cnx = None

try:
    cnx = mysql.connector.connect(
        user='',    # ユーザー名
        passwd='',  # パスワード
        host='',    # データベースホスト
        db=''       # データベース名
    )

    if cnx.is_connected:
        print("Content-Type: text/html; charset=UTF-8\r\n")
        print("Connected!")

except mysql.connector.Error as e:
    if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("User name or password is invalid.")
    elif e.errno == errorcode.ER_ACCOUNT_HAS_BEEN_LOCKED:
        print("This account is locked.")
    else:
        print(e)

except Exception as e:
    print(f"Error Occurred: {e}")

finally:
    if cnx is not None and cnx.is_connected():
        cnx.close()

接続成功したら、以下が表示されます。

データベース

参考

python
【python】ロリポップサーバーでpythonファイルを表示させる方法
python
【python】ローカルサーバー(XAMPP)でMySqlに接続する方法

まとめ

  1. ロリポップでPythonが使えるが, SSH接続ができるのは、スタンダード以上のプランだけ
  2. SSHでmysql-connector-pythonをダウンロード
  3. レンタルサーバーのユーザー名、パスワード、ホスト名、データベース名を確認

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ