この技術ブログでは、Python を使用して MySQL データベースを操作する方法について説明します。最初に接続を確立する方法を説明し、次に基本的なデータベース操作 (テーブルの作成、データの挿入、データのクエリなど) を実行する方法を示します。最後に、詳細なコード例で学んだ内容を強化します。
目次
- 導入
- MySQL コネクタをインストールする
- 接続を確立する
- データベースを作成する
- テーブルを作成する
- データを挿入する
- クエリデータ
- データを更新する
- データを削除する
- 詳細なコードケース
- 要約する
1 はじめに
MySQL は、さまざまなアプリケーションや Web サイトで広く使用されているリレーショナル データベース管理システムです。Python には、MySQL データベースと対話するためのさまざまなライブラリが提供されています。この記事では、公式に推奨されているmysql-connector-python
ライブラリを使用します。
2.MySQLコネクタをインストールする
開始する前に、ライブラリがインストールされていることを確認してくださいmysql-connector-python
。インストールされていない場合は、次のコマンドを使用してインストールできます。
bash
复制代码
pip install mysql-connector-python
3. 接続を確立する
MySQL データベースと対話するには、まず接続を確立する必要があります。次のコードは、このメソッドを使用してmysql.connector.connect()
接続を確立する方法を示しています。
python
复制代码
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password"
)
print("Connected to MySQL server!")
cnx.close()
4. データベースを作成する
MySQL サーバーに接続したら、新しいデータベースを作成できます。次のコードは、ステートメントを使用して名前を付けたデータベースをCREATE DATABASE
作成する方法を示しています。mydb
python
复制代码
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password"
)
cursor = cnx.cursor()
cursor.execute("CREATE DATABASE mydb")
print("Database 'mydb' created!")
cnx.close()
5. テーブルの作成
データベースを作成したら、その中にテーブルを作成する必要があります。users
次のコードは、 という名前のテーブルを作成しid
、name
それに列を追加する方法を示していますemail
。
python
复制代码
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
cursor.execute("""
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
)
""")
print("Table 'users' created!")
cnx.close()
6. データの挿入
テーブルが作成されたら、そこにデータを挿入できます。users
次のコードは、テーブルにデータを挿入する方法を示しています。
python
复制代码
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
val = ("John Doe", "[email protected]")
cursor.execute(sql, val)
cnx.commit()
print(f"{cursor.rowcount} record(s) inserted!")
cnx.close()
7. データのクエリ
SELECT
ステートメントを使用してテーブルのデータをクエリできます。users
次のコードは、テーブルのすべてのデータをクエリする方法を示しています。
python
复制代码
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
cursor.execute("SELECT * FROM users")
for row in cursor.fetchall():
print(row)
cnx.close()
8. データの更新
テーブル内のデータを更新するには、UPDATE
ステートメントを使用できます。users
次のコードは、テーブル内のデータを更新する方法を示しています。
python
复制代码
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
sql = "UPDATE users SET email = %s WHERE name = %s"
val = ("[email protected]", "John Doe")
cursor.execute(sql, val)
cnx.commit()
print(f"{cursor.rowcount} record(s) updated!")
cnx.close()
9. データの削除
テーブルからデータを削除するには、DELETE
ステートメントを使用できます。users
次のコードは、テーブルから行を削除する方法を示しています。
python
复制代码
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
cursor = cnx.cursor()
sql = "DELETE FROM users WHERE name = %s"
val = ("John Doe",)
cursor.execute(sql, val)
cnx.commit()
print(f"{cursor.rowcount} record(s) deleted!")
cnx.close()
10. 詳細なコードケース
このセクションでは、実践的な例で学んだ内容を強化します。ユーザー情報をデータベースに追加し、必要に応じてその情報をクエリ、更新、または削除できる単純なアプリケーションを作成します。
python
复制代码
import mysql.connector
def connect_to_db():
return mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="mydb"
)
def create_user(name, email):
cnx = connect_to_db()
cursor = cnx.cursor()
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
val = (name, email)
cursor.execute(sql, val)
cnx.commit()
cnx.close()
def get_all_users():
cnx = connect_to_db()
cursor = cnx.cursor()
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
cnx.close()
return result
def update_user_email(name, new_email):
cnx = connect_to_db()
cursor = cnx.cursor()
sql = "UPDATE users SET email = %s WHERE name = %s"
val = (new_email, name)
cursor.execute(sql, val)
cnx.commit()
cnx.close()
def delete_user(name):
cnx = connect_to_db()
cursor = cnx.cursor()
sql = "DELETE FROM users WHERE name = %s"
val = (name,)
cursor.execute(sql, val)
cnx.commit()
cnx.close()
# 添加用户
create_user("Alice", "[email protected]")
create_user("Bob", "[email protected]")
# 查询所有用户
users = get_all_users()
print("All users:")
for user in users:
print(user)
# 更新用户邮箱
update_user_email("Alice", "[email protected]")
# 查询所有用户
users = get_all_users()
print("All users after update:")
for user in users:
print(user)
# 删除用户
delete_user("Bob")
# 查询所有用户
users = get_all_users()
print("All users after deletion:")
for user in users:
print(user)
11. まとめ
このブログでは、Python を使用して MySQL データベースを操作する方法を学びました。接続の確立、データベースとテーブルの作成、データの挿入、データのクエリ、データの更新、データの削除の方法について説明しました。最後に、詳細なコードケースを通じて学んだことを統合します。
mysql-connector-python
ライブラリの他の機能について詳しく知りたい場合は、公式ドキュメント「 MySQL Connector/Python Developer Guide」を参照してください。
Python に興味があり、Python を学習してより高い給与を獲得したい場合は、次の Python 学習教材セットが役立つはずです。
教材には、Python インストール パッケージ + アクティベーション コード、Python Web 開発、Python クローラー、Python データ分析、人工知能、機械学習、その他の学習チュートリアルが含まれます。基礎0の初心者でもわかりやすく、チュートリアルに沿って基礎0から体系的にPythonを学べます!
1.Pythonの全方位学習ルート
Python の全方位ルートは、Python の一般的に使用される技術的なポイントを整理して、さまざまな分野の知識ポイントをまとめることです。その有用性は、上記の知識ポイントに応じて、対応する学習リソースを見つけて確実に学習できることにあります。より包括的に。
2.Python学習ソフト
労働者が良い仕事をしたいなら、まず道具を研ぐ必要があります。Pythonを学ぶのによく使われる開発ソフトはこちら!
3. Python入門学習ビデオ
基礎0から始めるのに適した学習動画も多数あり、これを読めば簡単にPythonを始められますよ~
4. Python の演習
各ビデオレッスンの後には、対応する練習問題があり、学習結果をテストできます。
五、Python実戦事例
光学理論は役に立ちません。学んだことを実践に応用するには、それに沿ってコーディングを学び、自分で実行する必要があります。現時点では、いくつかの実践的な事例から学ぶことができます。こんな情報も載ってますよ~
6. Python インタビュー資料
Python を学んだ後は、そのスキルを活かして仕事を見つけることができます。以下の面接の質問はすべてアリババ、テンセント、バイトなどの一流インターネット企業からのものであり、アリの上司からの信頼できる回答も含まれており、この一連の面接資料を読めば、誰もが満足のいく仕事を見つけることができると信じています。
7. 情報収集
上記の完全版 Python の学習教材一式は CSDN 公式にアップロードされており、必要な方は以下の CSDN 公式認定の QR コードを WeChat でスキャンして無料で入手できます。