GVKun编程网logo

Python将numpy数组插入sqlite3数据库(python numpy数组添加元素)

14

此处将为大家介绍关于Python将numpy数组插入sqlite3数据库的详细内容,并且为您解答有关pythonnumpy数组添加元素的相关问题,此外,我们还将为您介绍关于PythonSQLite3数

此处将为大家介绍关于Python将numpy数组插入sqlite3数据库的详细内容,并且为您解答有关python numpy数组添加元素的相关问题,此外,我们还将为您介绍关于Python SQLite3数据库操作类分享、Python SQLite3数据库查询绑定错误、Python Sqlite3数据库相关操作、python – sqlite3数据库被锁定的有用信息。

本文目录一览:

Python将numpy数组插入sqlite3数据库(python numpy数组添加元素)

Python将numpy数组插入sqlite3数据库(python numpy数组添加元素)

我试图在sqlite3数据库中存储大约1000个浮点数的numpy数组,但我不断收到错误“
InterfaceError:错误绑定参数1-可能是不受支持的类型”。

我给人的印象是BLOB数据类型可以是任何东西,但绝对不适用于numpy数组。这是我尝试过的:

import sqlite3 as sql
import numpy as np
con = sql.connect('test.bd',isolation_level=None)
cur = con.cursor()
cur.execute("CREATE TABLE foobar (id INTEGER PRIMARY KEY,array BLOB)")
cur.execute("INSERT INTO foobar VALUES (?,?)",(None,np.arange(0,500,0.5)))
con.commit()

我是否可以使用另一个模块将numpy数组放入表中?还是可以将numpy数组转换为sqlite可以接受的Python中的另一种形式(例如可以拆分的列表或字符串)?性能不是重点。我只是想让它工作!

谢谢!

Python SQLite3数据库操作类分享

Python SQLite3数据库操作类分享

接触Python时间也不是很长的,最近有个项目需要分析数据,于是选用Python为编程语言,除了语言特性外主要还是看重Python对于sqlite3数据库良好的支持能力了,因为需要灵活处理大量的中间数据。

刚开始一些模块我还乐此不疲的写sql语句,后来渐渐厌倦了,回想到以前捣鼓C#的时候利用反射初步构建了个SQL查询构造器,直到发现linq,于是放弃了这个计划,当然微软后来又推出了Entity Framework,这些都是后话了,而且现在我对微软的东西兴趣不是很大的,好了,扯多了,下面继续正文。

对了,再扯一句,优秀的博客程序Drupal也使用了类似的查询构造器进行数据库查询,避免直接写sql语句,另外这样做的一点点好处就是,可以一定程度的屏蔽平台相关性,对于数据库迁移还是有帮助的。

不过我今天介绍的数据库辅助类查询构造器是个很简单的东东,甚至只限于sqlite数据库,如果有童鞋感兴趣可以完善下,我目前只要操作sqlite顺手就可以了,对于比较大的数据库应用就直接上ORM吧。


先看代码:

复制代码 代码如下:

import sqlite3

# ***************************************************
# *
# * Description: Python操作sqlite3数据库辅助类(查询构造器)
# * Author: wangye
# *
# ***************************************************

def _wrap_value(value):
    return repr(value)

def _wrap_values(values):
    return list(map(_wrap_value,values))

def _wrap_fields(fields):
    for key,value in fields.items():
        fields[key] = _wrap_value(value)
    return fields

def _concat_keys(keys):
    return "[" + "],[".join(keys) + "]"

def _concat_values(values):
    return ",".join(values)

def _concat_fields(fields,operator = (None,",")):
    if operator:
        unit_operator,group_operator = operator
    # fields = _wrap_fields(fields)
    compiled = []
    for key,value in fields.items():
        compiled.append("[" + key + "]")
        if unit_operator:
            compiled.append(unit_operator)
            compiled.append(value)
        compiled.append(group_operator)
    compiled.pop() # pop last group_operator
    return " ".join(compiled)

class DataCondition(object):
    """
        本类用于操作sql构造器辅助类的条件语句部分

        例如:
        DataCondition(("=","AND"),id = 26)
        DataCondition(("=",True,id = 26)
    """

    def __init__(self,operator = ("=",ingroup = True,**kwargs):
        """
            构造方法
            参数:
                operator 操作符,分为(表达式操作符,条件运算符)
                ingroup  是否分组,如果分组,将以括号包含
                kwargs   键值元组,包含数据库表的列名以及值
                         注意这里的等于号不等于实际生成sql语句符号
                         实际符号是由operator[0]控制的
            例如:
            DataCondition(("=",id = 26)
            (id=26)
            DataCondition((">","OR"),id = 26,age = 35)
            (id>26 OR age>35)
            DataCondition(("LIKE",False,name = "John",company = "Google")
            name LIKE 'John' OR company LIKE "Google"
        """
        self.ingroup = ingroup
        self.fields = kwargs
        self.operator = operator

    def __unicode__(self):
        self.fields = _wrap_fields(self.fields)
        result = _concat_fields(self.fields,self.operator)
        if self.ingroup:
            return "(" + result + ")"
        return result

    def __str__(self):
        return self.__unicode__()

    def toString(self):
        return self.__unicode__()

class DataHelper(object):

    """
        sqlite3 数据查询辅助类
    """

    def __init__(self,filename):
        """
            构造方法
            参数: filename 为sqlite3 数据库文件名
        """
        self.file_name = filename

    def open(self):
        """
            打开数据库并设置游标
        """
        self.connection = sqlite3.connect(self.file_name)
        self.cursor = self.connection.cursor()
        return self

    def close(self):
        """
            关闭数据库,注意若不显式调用此方法,
            在类被回收时也会尝试调用
        """
        if hasattr(self,"connection") and self.connection:
            self.connection.close()

    def __del__(self):
        """
            析构方法,做一些清理工作
        """
        self.close()

    def commit(self):
        """
            提交事务
            SELECT语句不需要此操作,默认的execute方法的
            commit_at_once设为True会隐式调用此方法,
            否则就需要显示调用本方法。
        """
        self.connection.commit()

    def execute(self,sql = None,commit_at_once = True):
        """
            执行sql语句
            参数:
                sql  要执行的sql语句,若为None,则调用构造器生成的sql语句。
                commit_at_once 是否立即提交事务,如果不立即提交,
                对于非查询操作,则需要调用commit显式提交。
        """
        if not sql:
            sql = self.sql
        self.cursor.execute(sql)
        if commit_at_once:
            self.commit()

    def fetchone(self,sql = None):
        """
            取一条记录
        """
        self.execute(sql,False)
        return self.cursor.fetchone()

    def fetchall(self,sql = None):
        """
            取所有记录
        """
        self.execute(sql,False)
        return self.cursor.fetchall()

    def __concat_keys(self,keys):
        return _concat_keys(keys)

    def __concat_values(self,values):
        return _concat_values(values)

    def table(self,*args):
        """
            设置查询的表,多个表名用逗号分隔
        """
        self.tables = args
        self.tables_snippet = self.__concat_keys(self.tables)
        return self

    def __wrap_value(self,value):
        return _wrap_value(value)

    def __wrap_values(self,values):
        return _wrap_values(values)

    def __wrap_fields(self,fields):
        return _wrap_fields(fields)

    def __where(self):
        # self.condition_snippet
        if hasattr(self,"condition_snippet"):
            self.where_snippet = " WHERE " + self.condition_snippet

    def __select(self):
        template = "SELECT %(keys)s FROM %(tables)s"
        body_snippet_fields = {
            "tables" : self.tables_snippet,
            "keys" : self.__concat_keys(self.body_keys),
        }
        self.sql = template % body_snippet_fields

    def __insert(self):
        template = "INSERT INTO %(tables)s (%(keys)s) VALUES (%(values)s)"
        body_snippet_fields = {
            "tables" : self.tables_snippet,
            "keys" : self.__concat_keys(list(self.body_fields.keys())),
            "values" : self.__concat_values(list(self.body_fields.values()))
        }
        self.sql = template % body_snippet_fields

    def __update(self):
        template = "UPDATE %(tables)s SET %(fields)s"
        body_snippet_fields = {
            "tables" : self.tables_snippet,
            "fields" : _concat_fields(self.body_fields,("=","))
        }
        self.sql = template % body_snippet_fields

    def __delete(self):
        template = "DELETE FROM %(tables)s"
        body_snippet_fields = {
            "tables" : self.tables_snippet
        }
        self.sql = template % body_snippet_fields

    def __build(self):
        {
            "SELECT": self.__select,
            "INSERT": self.__insert,
            "UPDATE": self.__update,
            "DELETE": self.__delete
        }[self.current_token]()

    def __unicode__(self):
        return self.sql

    def __str__(self):
        return self.__unicode__()

    def select(self,*args):
        self.current_token = "SELECT"
        self.body_keys = args
        self.__build()
        return self

    def insert(self,**kwargs):
        self.current_token = "INSERT"
        self.body_fields = self.__wrap_fields(kwargs)
        self.__build()
        return self

    def update(self,**kwargs):
        self.current_token = "UPDATE"
        self.body_fields = self.__wrap_fields(kwargs)
        self.__build()
        return self

    def delete(self,*conditions):
        self.current_token = "DELETE"
        self.__build()
        #if *conditions:
        self.where(*conditions)
        return self

    def where(self,*conditions):
        conditions = list(map(str,conditions))
        self.condition_snippet = " AND ".join(conditions)
        self.__where()
        if hasattr(self,"where_snippet"):
            self.sql += self.where_snippet
        return self

下面举几个例子供大家参考吧:

复制代码 代码如下:

db = DataHelper("/home/wangye/sample.db3")
db.open() # 打开数据库
db.execute("""
    CREATE TABLE [staffs] (
      [staff_id] INTEGER PRIMARY KEY AUTOINCREMENT,
      [staff_name] TEXT NOT NULL,
      [staff_cardnum] TEXT NOT NULL,
      [staff_reserved] INTEGER NOT NULL
)
""") # 直接执行sql语句,注意这里commit_at_once默认为True

db.table("staffs").insert(staff_name="John",staff_cardnum="1001",staff_reserved=0)
# 插入一条记录

rs = db.table("staffs").select("staff_id","staff_name").fetchall()
# 直接取出所有staff_id和staff_name

rs = db.table("staffs").select("staff_name").where(DataCondition(("=",id = 1)).fetchone()
# 取一条staff_id为1的staff_name

rs = db.table("staffs").select("staff_name").where(DataCondition(("<",id = 100),DataCondition(("=",staff_reserved = 1)).fetchone()
# 取一条id小于100并且staff_reserved为1的staff_name记录

db.close() # 关闭数据库

目前还没有让其支持星号(*)操作符,另外在多表同名列操作方面处理得也不是很好,这个只用于日常简单的脚本操作,最好不要用于生产环境,因为可能有未知问题。

Python SQLite3数据库查询绑定错误

Python SQLite3数据库查询绑定错误

idTag的数据类型必须是问题所在,要消除它,只需将查询更改为:

c.execute(query,(str(idTag),))

然后使用c.fetchone()而不是使用c.fetchall()并在列表上建立索引,然后查看并选择所需的必要数据。虽然,我认为您不需要索引,因为数据库中的唯一数据是单个用户ID,在这种情况下,我不会为此使用数据库,而只是将数据存储在某个地方并进行相同的检查。>

Python Sqlite3数据库相关操作

Python Sqlite3数据库相关操作

1、连接数据库: cx= sqlite3.connect(‘database.db’) ,cx是一个数据库连接对象,它有以下操作: commit()--事务提交 rollbac

1、连接数据库:

cx= sqlite3.connect(‘database.db’) ,cx是一个数据库连接对象,它有以下操作:

commit()--事务提交

rollback()--事务回滚

close()--关闭一个数据库连接

cursor()--创建一个游标

 


2、获得游标对象:

所有sql语句都要在游标对象下执行,用cu= cx.cursor()来定义了一个游标,游标对象有以下的操作:

execute()--执行sql语句

executemany--执行多条sql语句

close()--关闭游标

fetchone()--从结果中取一条记录

fetchmany()--从结果中取多条记录

fetchall()--从结果中取出多条记录

scroll()--游标滚动

 


3、sqlite3使用举例:

3.1、建表

cu.execute("""createtable catalog (

idinteger primary key,

pidinteger,

namevarchar(10) UNIQUE)""")

上面语句创建了一个叫catalog的表,它有一个主键id,一个pid,,和一个name,name是不可以重复的。

3.2、insert(插入)数据

>>>cu.execute("insert into catalog values(?,?,?)",(0, 0,''name1''))

>>>cu.execute("insert into catalog values(1, 0, ''hello'')")

>>>cx.commit()

如果你愿意,你可以一直使用cu游标对象。注意,对数据的修改必须要使用事务语句:commit()或rollback(),且对象是数据库连接对象,这里为cx。

3.3、select(选择)数据:

>>>cu.execute("select * from catalog;")

>>>cu.fetchall()

[(0,0, ''name2''), (1, 0, ''hello'')]

fetchall()返回结果集中的全部数据,结果为一个tuple的列表。每个tuple元素是按建表的字段顺序排列。注意,游标是有状态的,它可以记录当前已经取到结果的第几个记录了,因此,一般你只可以遍历结果集一次。在上面的情况下,如果执行fetchone()会返回为空。这一点在测试时需要注意。

>>>cu.execute("select * from catalog where id = 1")

>>>cu.fetchone()

(1,0, ''hello'')

对数据库没有修改的语句,执行后不需要再执行事务语句。

3.4、update(修改)数据:

>>>cu.execute("update catalog set where id =?",(1,))

>>>cx.commit()

>>>cu.execute("select * from catalog")

>>>cu.fetchone()

(0,0, ''name2'')

3.5、delete(删除)数据:

>>>cu.execute("delete from catalog where id = ?",(1,))

>>>cx.commit()

>>>cu.execute("select * from catalog")

>>>cu.fetchall()

[(0,0, ''name2'')]

linux

python – sqlite3数据库被锁定

python – sqlite3数据库被锁定

我必须从操作表中删除记录时出现数据库锁定错误.

在sqlite3数据库上有两个读写程序

一个是在sqlite3表上写入硬件操作结果的c程序,另一个是从sqlite读取记录并在完成作业后处理它们并删除行的python脚本.

但删除行时python脚本show database被锁定错误..

db name:db.db

数据库表:
表’行动''(
    ‘摆脱’INTEGER PRIMARY KEY AUTOINCREMENT,
    ‘所有者’INTEGER,
    ‘行动’文字,
    ‘node’TEXT,
    ‘价值’文字

python脚本:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
import time
import os.path
import requests
#import urllib.parse

#defines
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR+"/dbs/","db.db")
wd_file_path = os.path.join(BASE_DIR,"wd")
pid = os.getpid()
conn = sqlite3.connect(db_path,isolation_level=None,timeout=30000)
print ("Opened database successfully");
while True:
    res = conn.execute("select * from ''actions'' where ''owner''=''1'';")
    #conn.commit()
    data=res.fetchone()
    print(data)
    if (data is None) :
        print(''nothing @ ''+str(time.time()))
        with open(wd_file_path,''w'') as file_:
            file_.write("{''pid''=''"+str(pid)+"'',''time''=''"+str(time.time())+"''}")
        time.sleep(0.5)
    else:
        #print(data)
        r = requests.post("http://127.0.0.1/json.PHP",data={''act'': data[2],''val'': data[4]})
        #if (r.text == ''1''):
        conn.execute("delete from ''actions'' where ''rid''="+str(data[0])+";")
        conn.commit()
        #else:
        #   print(r.text)

你可以看到我在我的连接上放了isolation_level = None和timeout = 30000
但我多次得到数据库锁定错误

解决方法

考虑删除无限时True循环并使用 connection cursor执行和获取语句:

conn = sqlite3.connect(db_path,timeout=30000) 
print("Opened database successfully")

cur = conn.cursor()
cur.execute("select * from ''actions'' where ''owner''=''1'';") 

for data in cur.fetchall() 
  print(data) 

  if (data is None): 
    print(''nothing @ ''+str(time.time())) 
    with open(wd_file_path,''w'') as file_: 
      file_.write("{''pid''=''"+str(pid)+"'',''time''=''"+str(time.time())+"''}") 
    time.sleep(0.5) 
  else: 
    #print(data) 
    r = requests.post("http://127.0.0.1/json.PHP",''val'': data[4]}) 
    #if (r.text == ''1''): 
    cur.execute("delete from ''actions'' where ''rid''="+str(data[0])+";") 
    conn.commit() 
    #else: 
    # print(r.text)

cur.close()
conn.close()

今天关于Python将numpy数组插入sqlite3数据库python numpy数组添加元素的讲解已经结束,谢谢您的阅读,如果想了解更多关于Python SQLite3数据库操作类分享、Python SQLite3数据库查询绑定错误、Python Sqlite3数据库相关操作、python – sqlite3数据库被锁定的相关知识,请在本站搜索。

本文标签:

上一篇如何从Python中的文件路径提取文件夹路径?(python 从路径中获取文件名)

下一篇用于在JSON数组中查找元素的索引(用于在json数组中查找元素的索引是)