python 远程操作Sqlite3

本文介绍了一种通过Python实现的简单远程执行SQLite3操作的方法。该方案包括服务端与客户端两部分代码,服务端监听指定端口接收SQL指令并执行,客户端发送SQL指令并接收执行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://hi.baidu.com/jxhtest/item/a4eff7206daa09122a0f1cca

2011-11-09 18:00

python 远程操作Sqlite3

貌似Sqlite3不支持远程访问,于是自己写了个简单的可以远程执行SQL操作的程序。

服务端代码:

#!/usr/bin/python
#coding=utf8
#filename:sqlite_server.py
import socket,sqlite3
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 8001))
sock.listen(5)
def sqlite3_execute(db,sql):
    dbpath = "/root/db/"
    conn = sqlite3.connect(dbpath+db)
    c = conn.cursor()
    c.execute(sql)
    conn.commit()
    datas = c.fetchall()
    return datas
while True:
    connection,address = sock.accept()
    try:
        connection.settimeout(5)
        buf = connection.recv(1024)
        if "," in buf:
            db,sql = buf.split(",")
            try:
                datas = sqlite3_execute(db,sql)
                connection.send(str(datas))
            except sqlite3.OperationalError,e:
                connection.send(str(e))
        else:
            connection.send("string format error,not found ','!")
    except socket.timeout:
        print 'time out'
        connection.close()

 

客户端代码:

#!/usr/bin/python
#coding=utf8
#filename:sqlite_client.py
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('X.X.X.X', 8001))
time.sleep(2)
sock.send('baseinfo.db,select * from SYS_USERS')
datas = sock.recv(1024)
datas = eval(datas)
sock.close()
for data in  datas:
    print data

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值