云主机测评网云主机测评网云主机测评网

云主机测评网
www.yunzhuji.net

python 如何访问数据库

在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是数据库服务器的地址,userpasswd分别是用户名和密码,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
打赏
版权声明:主机测评不销售、不代购、不提供任何支持,仅分享信息/测评(有时效性),自行辨别,请遵纪守法文明上网。
文章名称:《python 如何访问数据库》
文章链接:https://www.yunzhuji.net/jishujiaocheng/137039.html

评论

  • 验证码