Python Database
Python Database
title: python-database
date: 2020-09-16 15:41:56
tags: Python
categories: Language
---
## sqlite api
[sqlite](https://docs.python.org/3/library/sqlite3.html)
```python
self.conn = sqlite3.connect('conf.db')
self.cursor = self.conn.cursor()
sql = """
create table if not exists t_measurements(f_id INTEGER PRIMARY KEY AUTOINCREMENT
NOT NULL,
f_solutionId INTEGER NOT NULL,
f_name CHAR(300) NOT NULL , f_measureType CHAR(100) NOT NULL , f_points CHAR(500)
NOT NULL );
"""
self.cursor.execute(sql)
sql = """
create table if not exists t_solution(f_id INTEGER PRIMARY KEY AUTOINCREMENT NOT
NULL,
f_name CHAR(300) NOT NULL , f_createDT CHAR(100) NOT NULL );
"""
self.cursor.execute(sql)
self.conn.commit()
```
<!-- more -->
### delete
```python
def delete_task(conn, id):
"""
Delete a task by task id
:param conn: Connection to the SQLite database
:param id: id of the task
:return:
"""
sql = 'DELETE FROM tasks WHERE id=?'
cur = conn.cursor()
cur.execute(sql, (id,))
conn.commit()
def delete_all_tasks(conn):
"""
Delete all rows in the tasks table
:param conn: Connection to the SQLite database
:return:
"""
sql = 'DELETE FROM tasks'
cur = conn.cursor()
cur.execute(sql)
conn.commit()
```
### 插入
```python
sql = 'insert into t_solution(f_id , f_name , f_createDT) values (?,?,?)'
self.cursor.execute(sql, (None, new_name, dt))
self.conn.commit()
self.cursor.lastrowid
```
## records
用了一下 不好用,例子很少,常用的功能找起来费劲
Records 的特点:
```python
pip install records
```
- 连接数据库,返回 DB 数据库对象。
- 使用 query 方法执行 SQL 语句。
### sqlite
#### connect
```python
self.db = records.Database('sqlite:///conf.db')
```
```python
sql = """create table if not exists t_measurements(f_id INTEGER PRIMARY KEY
AUTOINCREMENT NOT NULL,
f_name CHAR(300) NOT NULL , f_measureType CHAR(100) NOT NULL , f_points CHAR(500)
NOT NULL );
"""
self.db.query(sql)
```
#### select
```python
sql = 'select * from t_solution;'
for row in self.cursor.execute(sql):
self.solution_dict[row[1]] = {'id': row[0], 'name': row[1], 'createDT':
row[2]}
self.mlbSolution.insert('end', *map(unicode, (row[1], row[2])))
```
#### 统计行数
```python
sql = 'select COUNT(*) from t_config;'
self.cursor.execute(sql)
cur_result = self.cursor.fetchone()
if not cur_result or 0 == cur_result[0]:
sql = 'insert into t_config(f_id,f_devIp,f_devPort) values (?,?,?)'
self.cursor.execute(sql, (None, '', ''))
self.conn.commit()
```
#### insert
```python
sql = 'insert into t_solution(f_id , f_name , f_createDT) values (?,?,?)'
self.cursor.execute(sql, (None, new_name, dt))
self.conn.commit()
```
#### 导出
```python
print(rows.export('json'))
print(rows.export('csv'))
```