python2.7 操作sqlite3 案例
时间: 2023-03-06 14:43:38 浏览: 113
答:我可以为您介绍一些python2.7操作sqlite3的案例,请参考以下示例:1.创建数据库:
import sqlite3
conn = sqlite3.connect('test.db')2.创建表:
cur = conn.cursor()
cur.execute('create table user (id varchar(20) primary key, name varchar(20))')3.插入数据:
cur.execute('insert into user (id, name) values (\'1\', \'Michael\')')4.查询数据:
cur.execute('select * from user where id=?', ('1',))
values = cur.fetchall()
print(values)5.更新数据:
cur.execute('update user set name=? where id=?', ('Jack', '1'))6.删除数据:
cur.execute('delete from user where id=?', ('1',))7.关闭数据库:
cur.close()
conn.commit()
conn.close()
相关问题
python 操作sqlite3
您好!要在Python中操作SQLite3数据库,您需要使用`sqlite3`模块。下面是一个示例代码来展示如何连接到SQLite3数据库、创建表并插入数据:
```python
import sqlite3
# 连接到数据库(如果数据库不存在,则会创建一个新的数据库)
conn = sqlite3.connect('example.db')
# 创建一个游标对象,用于执行SQL语句
cursor = conn.cursor()
# 创建一个表
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)''')
# 插入一条记录
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("John Doe", 25))
# 提交事务并关闭连接
conn.commit()
conn.close()
```
上述代码将创建一个名为`example.db`的SQLite3数据库文件,并在其中创建一个名为`users`的表。然后,它会将一条记录插入到该表中。
您可以根据需要执行其他的SQL操作,例如查询数据、更新数据等。详细的文档和示例可以在Python的官方文档中找到:[https://docs.python.org/3/library/sqlite3.html](https://docs.python.org/3/library/sqlite3.html)。
希望这对您有帮助!如果您有更多问题,请随时提问。
python sqlite3 基本操作
以下是Python3中使用sqlite3模块进行基本操作的示例:
1. 连接到数据库
```python
import sqlite3
conn = sqlite3.connect('example.db')
```
2. 创建表
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
conn.commit()
conn.close()
```
3. 插入数据
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
conn.commit()
conn.close()
```
4. 查询数据
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM stocks ORDER BY price'):
print(row)
conn.close()
```
5. 更新数据
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("UPDATE stocks SET qty = 200 WHERE symbol = 'RHAT'")
conn.commit()
conn.close()
```
6. 删除数据
```python
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("DELETE FROM stocks WHERE symbol = 'RHAT'")
conn.commit()
conn.close()
```