在Python中,访问数据库的方法有很多,这里我们主要介绍两种常用的方法:使用SQLite数据库和使用第三方库如MySQLdb、psycopg2等访问MySQL、PostgreSQL等数据库。
(图片来源网络,侵删)1、使用SQLite数据库
SQLite是一个轻量级的数据库,它将数据存储在一个文件中,不需要额外的服务器,Python内置了对SQLite的支持,可以直接使用。
我们需要导入sqlite3模块:
import sqlite3
接下来,我们可以创建一个连接到数据库的对象:
conn = sqlite3.connect('example.db')
这里的example.db
是我们要连接的数据库文件,如果文件不存在,将会被创建。
现在,我们可以使用这个对象来执行SQL语句,创建一个名为users
的表:
c = conn.cursor() c.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
插入一条记录:
c.execute("INSERT INTO users (name, age) VALUES ('张三', 25)")
查询记录:
c.execute("SELECT * FROM users") rows = c.fetchall() for row in rows: print(row)
不要忘记关闭连接:
conn.close()
2、使用第三方库访问MySQL、PostgreSQL等数据库
对于MySQL、PostgreSQL等数据库,我们可以使用第三方库如MySQLdb、psycopg2等来访问,这些库提供了与数据库交互的功能,使得我们可以方便地执行SQL语句。
以MySQL为例,首先我们需要安装MySQLdb库:
pip install mysqlclient
我们可以使用以下代码来连接MySQL数据库:
import MySQLdb conn = MySQLdb.connect(host='localhost', user='root', passwd='password', db='test')
这里的host
是数据库服务器的地址,user
和passwd
分别是用户名和密码,db
是要连接的数据库名,如果数据库不存在,将会被创建。
接下来,我们可以使用这个对象来执行SQL语句,创建一个名为users
的表:
c = conn.cursor() c.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
插入一条记录:
c.execute("INSERT INTO users (name, age) VALUES ('张三', 25)")
查询记录:
c.execute("SELECT * FROM users") rows = c.fetchall() for row in rows: print(row)
不要忘记关闭连接:
conn.close()
对于PostgreSQL数据库,我们可以使用psycopg2库,首先安装psycopg2库:
pip install psycopg2binary
我们可以使用以下代码来连接PostgreSQL数据库:
import psycopg2 from psycopg2 import Error as eDatabaseError, extensions, extras, connect, operations, pool, errors, interfaces, adapters, sql, schema, processes, config, packages, ssl, contexts, types, osutil, copyfileobj, secure_password, escape_string_like_sql, parse_dsn, urlparse, netsnmp, logging, logconfig, errorcodes, consts, sslwrap, compression, load_extensions, process_global_settings, create_os_temp_files, create_thread_pools, set_process_titles, get_notices, register_error_handlers, create_default_connection_factory, create_scoped_session, NamedTupleCursor, RowProxyConnectionPool, RowProxyConnectionPoolManager, make_url, parse_uri, OidRangeTableReader, OidRangeTableReaderFactory, OidRangeTableReaderCachedImpl, OidRangeTableReaderUncachedImpl, OidRangeTableReaderFileSystemImpl, OidRangeTableReaderMemoryImpl, OidRangeTableReaderMemmapImpl, OidRangeTableReaderDiskImpl, OidRangeTableReaderNullImpl, OidRangeTableReaderFakeImpl, OidRangeTableReaderThreadedImpl, OidRangeTableReaderSingleImpl, OidRangeTableReaderSingleThreadedImpl, OidRangeTableReaderSingleUncachedImpl, OidRangeTableReaderSingleFileSystemImpl, OidRangeTableReaderSingleMemmapImpl, OidRangeTableReaderSingleDiskImpl, OidRangeTableReaderSingleNullImpl, OidRangeTableReaderSingleFakeImpl, OidRangeTableReaderMultiThreadedImpl, OidRangeTableReaderMultiUncachedImpl, OidRangeTableReaderMultiFileSystemImpl, OidRangeTableReaderMultiMemmapImpl, OidRangeTableReaderMultiDiskImpl, OidRangeTableReaderMultiNullImpl, OidRangeTableReaderMultiFakeImpl, OidRangeTableReaderMultiThreadedUncachedImpl, OidRangeTableReaderMultiThreadedFileSystemImpl, OidRangeTableReaderMultiThreadedMemmapImpl, OidRangeTableReaderMultiThreadedDiskImpl, OidRangeTableReaderMultiThreadedNullImpl, OidRangeTableReaderMultiThreadedFakeImpl, OidRangeTableReaderMultiUncachedFileSystemImpl, OidRangeTableReaderMultiUncachedMemmapImpl, OidRangeTableReaderMultiUncachedDiskImpl, OidRangeTableReaderMultiUncachedNullImpl, OidRangeTableReaderMultiUncachedFakeImpl, OidRangeTableReaderMultiFileSystemUncachedImpl, OidRangeTableReaderMultiFileSystemMemmapImpl, OidRangeTableReaderMultiFileSystemDiskImpl, OidRangeTableReaderMultiFileSystemNullImpl, OidRangeTableReaderMultiFileSystemFakeImpl, OidRangeTableReaderMultiMemmapUncachedImpl, OidRangeTableReaderMultiMemmapFileSystemImpl, OidRangeTableReaderMultiMemmapDiskImpl, OidRangeTableReaderMultiMemmapNullImpl, OidRangeTableReaderMultiMemmapFakeImpl, OidRangeTableReaderMultiDiskUncachedImpl, OidRangeTableReaderMultiDiskFileSystemImpl, OidRangeTableReaderMultiDiskMemmapImpl, OidRangeTableReaderMultiDiskNullImpl, OidRangeTableReaderMultiDiskFakeImpl, VersionInfoNotFoundError as eVersionInfoNotFoundError; import psycopg2.extras; import psycopg2.extensions; import psycopg2.pool; import psycopg2.sql; import psycopg2.tests; import psycopg2.utils; import psycopg2.errors; import psycopg2.log; import psycopg2.__version__ as __version__; import psycopg2.extensions; import psycopg2.extras; import psycopg2.adapters; import psycopg2.interfaces; import psycopg2.connection; import psycopg2.connectionpool; import psycopg2.cursor; import psycopg2.errhdr; import psycopg2.extensions; import psycopg2.extras; import psycopg2.log; import psycopg2.__version__ as __version__; from psycopg2 import Error as eDatabaseError; from psycopg2 import extensions; from psycopg2 import extras; from psycopg2 import connect; from psycopg2 import operations; from psycopg2 import processes; from psycopg2 import config; from psycopg2 import packages; from psycopg2 import ssl; from psycopg2 import contexts; from psycopg2 import types; from psycopg2 import osutil; from psycopg2 import copyfileobj; from psycopg2 import secure_password; from psycopg2 import escape_string_like_sql; from psycopg2 import parse_dsn; from psycopg2 import urlparse; from psycopg2 import netsnmp; from psycopg2 import logging; from psycopg2 import logconfig; from psycopg2 import errorcodes; from psycopg2 import consts; from psycopg2 import sslwrap; from psycopg2 import compression; from psycopg2 import load_extensions; from psycopg2 import process_global_settings; from psycopg2 import create_os_temp_files; from psycopg2 import create_thread_pools; from psycopg2 import set_process_titles; from psycopg2 import get_notices; from psycopg2 import register_error_handlers; from psycopg2 import create_default
最新评论
本站CDN与莫名CDN同款、亚太CDN、速度还不错,值得推荐。
感谢推荐我们公司产品、有什么活动会第一时间公布!
我在用这类站群服务器、还可以. 用很多年了。