目次
1. Python は MySQL データベースに接続します
データベースの紹介
リレーショナル データベースは、リレーショナル モデルに基づいたデータベースであり、リレーショナル モデルは 2 次元のテーブルを通じて格納されます。したがって、リレーショナル データベース内のデータは、行と列で構成されるテーブルに格納されます。各列はフィールドと列を表します。各行はレコードを表します。
リレーショナル データベースには、SQLite、MySQL、Oracle、SQL Server、DB2 など、さまざまな種類があります。
1. Python は MySQL データベースに接続します
Python でデータベースに接続する例:
```python
import pymysql
db = pymysql.connect(host='localhost',user='root',password='password',port=3306) #连接数据库
cursor = db.cursor() #获取操作游标
cursor.execute('SELECT VERSION()')
data = cursor.fetchone() #得到第一条数据
print('Database verison:',data)
cursor.execute('CREATE DATABASE spiders DEFAULT CHARACTER SET utf8mb4') #传入SQL语句,创建数据库
db.close() #关闭数据库
2.PythonでMySQLテーブルを作成する
テーブルを作成します。
db = pymysql.connect(host='localhost',user='root',password='password',port=3306) #连接数据库
cursor = db.cursor() #获取操作游标
cursor.execute('use spiders;')
sql = 'CREATE TABLE if NOT EXISTS students (id VARCHAR(225) NOT NULL,NAME VARCHAR(225) NOT NULL,age INT NOT NULL,PRIMARY KEY(id));'
cursor.execute(sql)
db.close() #关闭数据库
3. データを挿入する
id = '20210001'
name = 'Bob'
age = 20
db = pymysql.connect(host='localhost',user='root',password='password',port=3306) #连接数据库
cursor = db.cursor() #获取操作游标
cursor.execute('use spiders;')
sql = 'INSERT INTO students(id,name,age) values (%s,%s,%s)'
try:
cursor.execute(sql,(id,name,age))
db.commit()#提交,做出修改
except:
print('error')
db.rollback()#回滚
db.close() #关闭数据库
Commit() と mysql の送信が必要です。そうでない場合、テーブルは変更されません。
一般に、上記の挿入方法は柔軟性がありません。Python がデータベースに挿入するときは、動的サブディバイダーを渡して、このディクショナリに基づいて SQL ステートメントを構築させることができます。これは一般的な挿入方法です。
data = {
'id': '20220003',
'name': 'Link',
'age':20
}
table = 'students'
keys = ','.join(data.keys())
values = ','.join(['%s'] * len(data))
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table,keys=keys,values=values)
print(keys)
print(values)
print(sql)
得到输出:
id,name,age
%s,%s,%s
INSERT INTO students(id,name,age) VALUES (%s,%s,%s)
#则插入操作就可以这样写
data = {
'id': '20220003',
'name': 'Link',
'age':20
}
table = 'students'
keys = ','.join(data.keys())
values = ','.join(['%s'] * len(data))
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table,keys=keys,values=values)
print(keys)
print(values)
print(sql)
db = pymysql.connect(host='localhost',user='root',password='password',port=3306) #连接数据库
cursor = db.cursor() #获取操作游标
cursor.execute('use spiders;')
try:
cursor.execute(sql,tuple(data.values()))
db.commit()#提交,做出修改
print('Successful')
except:
print('error')
db.rollback()#回滚
db.close() #关闭数据库
4. データの更新
また、ディクショナリを使用して SQL ステートメントを構築し、重複排除手法を使用します。データが存在する場合はデータを更新し、データが存在しない場合はデータを挿入します。例は次のとおりです。
data = {
'id': '20220015',
'name': 'Link',
'age':30
}
table = 'students'
keys = ','.join(data.keys())
values = ','.join(['%s'] * len(data))
sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE '.format(table=table,keys=keys,values=values)
updata = ','.join(["{key} = %s".format(key= key) for key in data.keys()])
print(updata)
sql += updata
print(keys)
print(values)
print(sql)
db = pymysql.connect(host='localhost',user='root',password='password',port=3306) #连接数据库
cursor = db.cursor() #获取操作游标
cursor.execute('use spiders;')
try:
cursor.execute(sql,tuple(data.values())*2) #因为有6个%s,则插入的元组需要翻倍
db.commit()#提交,做出修改
print('Successful')
except:
print('error')
db.rollback()#回滚
db.close() #关闭数据库
この方法で記述する利点は、主キーが存在しない場合にデータを挿入し、主キーが存在する場合にデータを更新できることです。
5. データの削除
データを削除するには、DELETE ステートメントを直接使用します。
例:
table = 'students'
condition = 'age >= 25'
sql = 'DELETE FROM {table} WHERE {condition}'.format(table = table,condition = condition)
print(sql)
db = pymysql.connect(host='localhost',user='root',password='password',port=3306) #连接数据库
cursor = db.cursor() #获取操作游标
cursor.execute('use spiders;')
try:
cursor.execute(sql)
db.commit()#提交,做出修改
print('Delete successfully')
except:
print('error')
db.rollback()#回滚
db.close() #关闭数据库
6. データのクエリ
MySQL クエリ操作は select ステートメントを使用し、Python コードを記述するときに、コミット関数 commit() を使用する必要はなくなりました。rowcount 属性を呼び出して返された結果の数を取得し、fetchone() メソッドを使用して最初の結果を取得できます。レコードを作成し、fetchall() メソッドを使用してすべてのクエリ結果を取得します。
例は次のとおりです。
table = 'students'
conditions = 'age >= 20'
sql = 'SELECT * FROM {table} WHERE {conditions}'.format(table = table,conditions = conditions)
print(sql)
db = pymysql.connect(host='localhost',user='root',password='password',port=3306) #连接数据库
cursor = db.cursor() #获取操作游标
try:
cursor.execute('use spiders')
cursor.execute(sql) #传入SQL语句
print('Count: ', cursor.rowcount)
one = cursor.fetchone()
print('One:',one)
results = cursor.fetchall()
print('Results:',results)
print('Results type:', type(results))
for result in results:
print(result)
except:
print('Error')
ここでの fetchall メソッドは、前の fetchone メソッドがすでに結果を取得しているため、すべての結果を取得するわけではなく、カーソルが下に移動します。再度 fetchall メソッドを使用すると、最初のレコード以降のレコードしか取得できません。
fetchall はタプルを返しますが、これは多くのスペースを占有します。通常は、while ループ ステートメントと fetchone メソッドを使用して各レコードを取得することをお勧めします。
table = 'students'
conditions = 'age >= 20'
sql = 'SELECT * FROM {table} WHERE {conditions}'.format(table = table,conditions = conditions)
print(sql)
db = pymysql.connect(host='localhost',user='root',password='password',port=3306) #连接数据库
cursor = db.cursor() #获取操作游标
try:
cursor.execute('use spiders')
cursor.execute(sql) #传入SQL语句
print('Count: ', cursor.rowcount)
one = cursor.fetchone()
while one:
print('One:',one)
one = cursor.fetchone()
# results = cursor.fetchall()
# print('Results:',results)
# print('Results type:', type(results))
# for result in results:
# print(result)
except:
print('Error')
```