導入
PyMySQL は、Python の人気のある MySQL データベース ドライバーであり、MySQL データベースの接続、クエリ、更新に便利な方法を提供します。この記事では、PyMySQL のインストール、データベースへの接続、クエリと更新操作の実行など、PyMySQL を使用して MySQL データベースにアクセスするための詳細なガイドを提供します。
環境整備
始める前に、PyMySQL ライブラリがインストールされていることを確認する必要があります。pip コマンドを使用してインストールできます。
pip install pymysql
データベースに接続する
まず、MySQL データベースへの接続を確立する必要があります。PyMySQL ライブラリを使用したサンプルコードは次のとおりです。
pymysql.connect(
host = 'localhost',
port = 3306,
user = 'root',
password = '123456',
db ='students',
charset = 'utf8'
)
connect
メソッドを呼び出してconnect
オブジェクトを生成し、このオブジェクトを通じてデータベースにアクセスします。
connect
メソッドの主なパラメータ
user
、データベースにアクセスするユーザーpassword
、データベースにアクセスするためのパスワードhost
、Mysql データベース サービスが配置されているホストport
、Mysql データベース サービスのポート番号、デフォルト値は 3306db
、データベース名charset
、文字コード
オブジェクトを接続する
- メソッドを使用して
connect()
データベースに正常に接続すると、connect()
メソッドはconnect()
オブジェクトを返します。 - データベースと通信するとき、
connect
SQL クエリ コマンドがオブジェクトに送信され、connect
オブジェクトは SQL クエリの結果を受け取ります。
一般的な方法
close()
、データベース接続を閉じますcommit()
、現在のトランザクションをコミットしますrollback()
、現在のトランザクションをキャンセルしますcursor()
、SQLクエリコマンドを実行するためのカーソルオブジェクトを作成します。
カーソルオブジェクト
カーソル オブジェクトは、SQL コマンドを実行し、SQL クエリの結果を取得するために使用されます。
一般的な方法
close()
、カーソルオブジェクトを閉じますexecute()
、データベースクエリまたはコマンドを実行します。fetchone()
、結果セットの次の行を返します。fetchall()
、結果セット内のすべての行を返します。
データベースの作成
3 つのフィールドを含む というstudents
ライブラリとというテーブルを作成します。コードは次のとおりです。students
id
name
age
db = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='1234567890',
db='students',
charset='utf8'
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
sql = """SET character_set_database=utf8;
SET character_set_server=utf8;
DROP DATABASE IF EXISTS students;
CREATE DATABASE students;
USE school;"""
lists = sql.split("\n")
for i in lists:
cursor.execute(i)
create_sql = """
CREATE TABLE students(
id VARCHAR(32),
name VARCHAR(32),
age INT
);
"""
cursor.execute(create_sql)
insert_sql = """
INSERT INTO students(id, name, age) VALUES ('202301', '穆勒', '18');
"""
cursor.execute(insert_sql)
db.commit()
db.close()
クエリデータ
データをクエリする前に、まずデータベースに接続する必要があります。データベース接続が確立されると、さまざまなクエリ操作を実行できるようになります。
db = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='1234567890',
db='students',
charset='utf8'
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
フェッチオールマッチ
一致する結果をすべて返す
sql = "select * from students;"
rows = cursor.execute(sql)
# 记录数
print("there are %d students" % rows)
# 可迭代对象
students = cursor.fetchall()
# 循环输出
for i in students:
print(i)
# 输出结果
there are 1 students
('202301', '穆勒', 18)
フェッチョネマッチ
レコードを返す
# 查询数据 - fetchone
sql = "select * from students;"
rows = cursor.execute(sql)
# 根据记录数循环
for i in range(rows):
student = cursor.fetchone()
print(student)
# 输出结果
('202301', '穆勒', 18)
フェッチメニーマッチ
返すレコードの数はカスタマイズ可能
# 查询数据 - fetchmany
sql = "select * from students;"
rows = cursor.execute(sql)
# 可迭代对象
students = cursor.fetchmany(3)
# 循环结果集
for i in students:
print(i)
# 输出结果
('202301', '穆勒', 18)
データの挿入
db = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='1234567890',
db='students',
charset='utf8'
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 增加数据
id = 202302
name = "基米希"
age = 24
sql = 'insert into students(id,name,age) VALUES("%s", "%s", %d)' % (id, name, age)
# 执行 insert sql
rows = cursor.execute(sql)
# 查看 insert 语句返回结果,其实就是执行成功了多少条数据
print('Insert %d students' % rows)
# 只有调用了 commit 方法才能将数据落盘,即提交 insert 操作
db.commit()
# 输出结果
Insert 1 students
データを変更する
db = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='1234567890',
db='students',
charset='utf8'
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 更新数据
id = 202302
name = "基米希"
age = 16
sql = 'UPDATE students SET name="%s", age=%d WHERE sno="%s"' % (name, age, id)
# 执行 update sql
rows = cursor.execute(sql)
# 返回成功修改记录的条数
print('update %d students' % rows)
# 调用 commit,才会将 update 操作提交
db.commit()
# 输出结果
update 1 students
データを削除する
db = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='1234567890',
db='students',
charset='utf8'
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 更新数据
sno = 202302
name = "小菠萝"
age = 14
sql = 'DELETE FROM students'
# 执行 delete sql
rows = cursor.execute(sql)
# 返回成功修改记录的条数
print('delete %d students' % rows)
# 调用 commit,才会将 delete 操作提交
db.commit()
# 输出结果
delete 2 students
要約する
PyMySQL
この記事では、アクションデータベースを使用するための詳細な手順を説明しますMySQL
。インストールから始まりPyMySQL
、データベースへの接続、クエリの実行、操作の追加、変更、削除は、PyMySQL を使用して MySQL データベースにアクセスするために必要な主要な手順です。この記事が、PyMySQL を使用して MySQL データベースを簡単に操作し、データの保存と取得のニーズを達成するのに役立つことを願っています。
最後に、私の記事を注意深く読んでくださった皆さんに感謝します。互恵性は常に必要です。それほど価値のあるものではありませんが、使用できる場合は、直接受け取ることができます。
この情報は、[ソフトウェア テスト] の友人にとって最も包括的かつ完全な準備倉庫となるはずです。この倉庫は、最も困難な旅を乗り越える何万人ものテスト エンジニアにも同行してきました。また、皆さんのお役に立てれば幸いです。