mysqlclient是Python的一个MySQL数据库驱动程序,它是Python DB API v2.0的实现之一。
它提供了一组函数和方法来连接MySQL数据库,并执行各种数据库操作。
Bash
import MySQLdb
conn = MySQLdb.connect(host='localhost', user='user', passwd='password', db='database')
Bash
cursor = conn.cursor()
cursor.execute('SELECT * FROM table')
result = cursor.fetchall()
cursor.execute('INSERT INTO table (column1, column2) VALUES (%s, %s)', ('value1', 'value2'))
conn.commit()
conn.rollback()
affected_rows = cursor.rowcount
last_insert_id = cursor.lastrowid
cursor.execute('UPDATE table SET column1 = %s WHERE column2 = %s', ('new_value', 'condition'))
cursor.execute('DELETE FROM table WHERE column = %s', ('value',))
data = [('value1', 'value2'), ('value3', 'value4')]
cursor.executemany('INSERT INTO table (column1, column2) VALUES (%s, %s)', data)
fields = cursor.description
cursor.execute('SHOW KEYS FROM table WHERE Key_name = "PRIMARY"')
primary_key = cursor.fetchone()[0]
cursor.execute('SHOW INDEX FROM table')indexes = cursor.fetchall()
cursor.execute('SHOW INDEX FROM table')
indexes = cursor.fetchall()
cursor.callproc('procedure_name', args)
output_param = cursor.fetchone()
try:
cursor.execute('START TRANSACTION')
# 执行其他SQL语句
cursor.execute('COMMIT')
except:
cursor.execute('ROLLBACK')
conn.set_charset('utf8')
conn.autocommit(True)
conn.set_timeout(10)
conn.query('SET SESSION query_cache_type = ON')
conn.set_max_connections(10)
cursor.close()
conn.close()
import MySQLdb
with MySQLdb.connect(host='localhost', user='user', passwd='password', db='database') as conn:
cursor = conn.cursor()
# 执行数据库操作
import MySQLdb
with MySQLdb.connect(host='localhost', user='user', passwd='password', db='database') as conn:
with conn.cursor() as cursor:
try:
cursor.execute('START TRANSACTION')
# 执行其他SQL语句
cursor.execute('COMMIT')
except:
cursor.execute('ROLLBACK')
conn.set_session(sql_mode='ANSI')
sql_mode = conn.get_session().get('sql_mode')
conn.set_connect_timeout(10)
connect_timeout = conn.get_connect_timeout()
conn.set_query_timeout(10)
query_timeout = conn.get_query_timeout()
conn.set_read_timeout(10)
read_timeout = conn.get_read_timeout()
conn.set_write_timeout(10)
write_timeout = conn.get_write_timeout()
conn.ssl_set(ca='path/to/ca.pem', cert='path/to/cert.pem', key='path/to/key.pem')
ssl_enabled = conn.ssl_in_use()Python
cursor.execute('SELECT * FROM table WHERE column = %s', ('value',))
cursor.execute('SELECT * FROM table WHERE column = %s', ('value',))
result = cursor.fetchall()
fields = [desc[0] for desc in cursor.description]
field_types = [desc[1] for desc in cursor.description]
import MySQLdb
from DBUtils.PersistentDB import PersistentDB
db_pool = PersistentDB(MySQLdb, host='localhost', user='user', passwd='password', db='database')
conn = db_pool.connection()
cursor = conn.cursor()
# 执行数据库操作
这些示例涵盖了mysqlclient模块的一系列功能,包括连接数据库、执行SQL语句、事务处理、批量插入、获取表信息等。希望对你有所帮助!