Python 的 cmd 模塊本身并不是為數據庫操作設計的,但它可以用于執行任何 Python 命令,包括與數據庫進行交互的命令。如果你想在命令行中使用 Python 來操作數據庫,你可以使用特定的數據庫驅動程序或庫,如 sqlite3(用于 SQLite 數據庫)、pymysql(用于 MySQL 數據庫)或 psycopg2(用于 PostgreSQL 數據庫)等。
以下是一些示例,展示了如何使用 Python 的 cmd 模塊與不同類型的數據庫進行交互:
import sqlite3
import cmd
class SQLiteCmd(cmd.Cmd):
prompt = 'sqlite> '
def do_create(self, arg):
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute(arg)
conn.commit()
conn.close()
print('Table created.')
def do_insert(self, arg):
conn = sqlite3.connect('example.db')
c = conn.cursor()
values = arg.split(',')
c.execute("INSERT INTO mytable (col1, col2) VALUES (?, ?)", values)
conn.commit()
conn.close()
print('Record inserted.')
def do_select(self, arg):
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute(arg)
rows = c.fetchall()
for row in rows:
print(row)
conn.close()
def do_exit(self, arg):
print('Exiting.')
return True
if __name__ == '__main__':
SQLiteCmd().cmdloop()
import pymysql
import cmd
class MySQLCmd(cmd.Cmd):
prompt = 'mysql> '
def do_connect(self, arg):
conn = pymysql.connect(host='localhost', user='user', password='password', db='database')
self.conn = conn
print('Connected.')
def do_create(self, arg):
with self.conn.cursor() as cursor:
cursor.execute(arg)
self.conn.commit()
print('Table created.')
def do_insert(self, arg):
with self.conn.cursor() as cursor:
values = arg.split(',')
cursor.execute("INSERT INTO mytable (col1, col2) VALUES (%s, %s)", values)
self.conn.commit()
print('Record inserted.')
def do_select(self, arg):
with self.conn.cursor() as cursor:
cursor.execute(arg)
rows = cursor.fetchall()
for row in rows:
print(row)
def do_exit(self, arg):
print('Exiting.')
self.conn.close()
return True
if __name__ == '__main__':
MySQLCmd().cmdloop()
import psycopg2
import cmd
class PostgreSQLCmd(cmd.Cmd):
prompt = 'postgres> '
def do_connect(self, arg):
conn = psycopg2.connect(host='localhost', user='user', password='password', dbname='database')
self.conn = conn
print('Connected.')
def do_create(self, arg):
with self.conn.cursor() as cursor:
cursor.execute(arg)
self.conn.commit()
print('Table created.')
def do_insert(self, arg):
with self.conn.cursor() as cursor:
values = arg.split(',')
cursor.execute("INSERT INTO mytable (col1, col2) VALUES (%s, %s)", values)
self.conn.commit()
print('Record inserted.')
def do_select(self, arg):
with self.conn.cursor() as cursor:
cursor.execute(arg)
rows = cursor.fetchall()
for row in rows:
print(row)
def do_exit(self, arg):
print('Exiting.')
self.conn.close()
return True
if __name__ == '__main__':
PostgreSQLCmd().cmdloop()
這些示例展示了如何使用 Python 的 cmd 模塊創建一個簡單的命令行界面,用于執行數據庫操作。你可以根據需要擴展這些示例,添加更多的命令和功能。