SQLite 基本使用

SQLite 基本使用

SQLite 基本使用

SQLite 是一个轻量级的嵌入式数据库,广泛用于移动应用、桌面应用和小型服务器应用中。以下是如何使用 SQLite 的基本步骤:

1. 安装 SQLite

在大多数操作系统中,SQLite 已经预装。如果没有,可以通过以下方式安装:

Windows: 下载 SQLite 预编译二进制文件 并解压到系统路径中。

macOS: 使用 Homebrew 安装:brew install sqlite

Linux: 使用包管理器安装,例如在 Ubuntu 上:sudo apt-get install sqlite3

2. 启动 SQLite 命令行工具

在终端或命令提示符中输入以下命令启动 SQLite 命令行工具:

sqlite3

这将启动 SQLite 命令行界面,并进入交互模式。

3. 创建或打开数据库

在 SQLite 命令行中,输入以下命令来创建或打开一个数据库文件:

sqlite3 your_database.db

如果 your_database.db 文件不存在,SQLite 会自动创建一个新的数据库文件。

4. 创建表

在 SQLite 中,使用 CREATE TABLE 语句来创建表。例如:

CREATE TABLE users (

id INTEGER PRIMARY KEY AUTOINCREMENT,

username TEXT NOT NULL,

email TEXT NOT NULL UNIQUE,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

5. 插入数据

使用 INSERT INTO 语句向表中插入数据。例如:

INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com');

6. 查询数据

使用 SELECT 语句查询数据。例如:

SELECT * FROM users;

这将返回 users 表中的所有记录。

7. 更新数据

使用 UPDATE 语句更新表中的数据。例如:

UPDATE users SET email = 'john.doe@example.com' WHERE username = 'john_doe';

8. 删除数据

使用 DELETE 语句删除表中的数据。例如:

DELETE FROM users WHERE username = 'john_doe';

9. 删除表

使用 DROP TABLE 语句删除整个表。例如:

DROP TABLE users;

10. 退出 SQLite

在 SQLite 命令行中,输入 .exit 或 .quit 退出。

11. 使用 SQLite 在编程语言中

SQLite 可以通过各种编程语言的库来操作。以下是一些常见语言的示例:

Python

使用 sqlite3 模块:

import sqlite3

# 连接到数据库

conn = sqlite3.connect('your_database.db')

cursor = conn.cursor()

# 创建表

cursor.execute('''CREATE TABLE IF NOT EXISTS users (

id INTEGER PRIMARY KEY AUTOINCREMENT,

username TEXT NOT NULL,

email TEXT NOT NULL UNIQUE,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')

# 插入数据

cursor.execute("INSERT INTO users (username, email) VALUES (?, ?)", ('john_doe', 'john@example.com'))

# 查询数据

cursor.execute("SELECT * FROM users")

rows = cursor.fetchall()

for row in rows:

print(row)

# 提交事务并关闭连接

conn.commit()

conn.close()

PHP

使用 SQLite3 类:

$db = new SQLite3('your_database.db');

// 创建表

$db->exec("CREATE TABLE IF NOT EXISTS users (

id INTEGER PRIMARY KEY AUTOINCREMENT,

username TEXT NOT NULL,

email TEXT NOT NULL UNIQUE,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");

// 插入数据

$db->exec("INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com')");

// 查询数据

$result = $db->query("SELECT * FROM users");

while ($row = $result->fetchArray()) {

print_r($row);

}

// 关闭连接

$db->close();

Java

使用 JDBC 驱动:

import java.sql.*;

public class SQLiteExample {

public static void main(String[] args) {

Connection conn = null;

try {

// 连接到数据库

conn = DriverManager.getConnection("jdbc:sqlite:your_database.db");

// 创建表

Statement stmt = conn.createStatement();

stmt.execute("CREATE TABLE IF NOT EXISTS users ("

+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "

+ "username TEXT NOT NULL, "

+ "email TEXT NOT NULL UNIQUE, "

+ "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");

// 插入数据

PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (username, email) VALUES (?, ?)");

pstmt.setString(1, "john_doe");

pstmt.setString(2, "john@example.com");

pstmt.executeUpdate();

// 查询数据

ResultSet rs = stmt.executeQuery("SELECT * FROM users");

while (rs.next()) {

System.out.println(rs.getInt("id") + " " + rs.getString("username") + " " + rs.getString("email"));

}

} catch (SQLException e) {

System.out.println(e.getMessage());

} finally {

try {

if (conn != null) conn.close();

} catch (SQLException ex) {

System.out.println(ex.getMessage());

}

}

}

}

12. 使用 SQLite 管理工具

除了命令行工具,还可以使用图形化的 SQLite 管理工具来更方便地操作数据库,例如:

DB Browser for SQLite: 一个开源的 SQLite 数据库管理工具,支持 Windows、macOS 和 Linux。

SQLite Studio: 另一个功能强大的 SQLite 管理工具。

这些工具提供了直观的界面,可以方便地创建、编辑和查询数据库。

总结

SQLite 是一个简单易用的嵌入式数据库,适合小型应用和原型开发。通过命令行工具或编程语言的库,你可以轻松地创建、管理和查询 SQLite 数据库。

react native如何使用sqllite

在 React Native (RN) 中使用 SQLite 数据库,可以通过第三方库来实现。以下是详细的步骤和示例,帮助你在 React Native 项目中集成和操作 SQLite 数据库。

1. 安装必要的依赖

首先,确保你已经安装了 Node.js 和 React Native CLI 或 Expo。然后,按照以下步骤安装所需的库。

使用 Expo 管理的项目

Expo 默认不支持直接使用原生模块,因此需要使用 expo-sqlite,它是 Expo SDK 的一部分。

expo install expo-sqlite

使用 React Native CLI 管理的项目

对于使用 React Native CLI 的项目,推荐使用 react-native-sqlite-storage 或 @react-native-async-storage/async-storage 结合 SQL 查询库(如 react-native-sqlite-2)。不过,目前更流行的是使用 expo-sqlite 或者通过 react-native 的原生模块集成。

这里以 expo-sqlite 为例,因为它适用于 Expo 和 React Native CLI 项目(通过手动配置原生模块)。

注意: 如果你使用的是纯 React Native CLI 项目,并且需要更高级的功能,可以考虑 react-native-sqlite-2 或 WatermelonDB 等库。不过,本文将以 expo-sqlite 为例进行说明。

2. 使用 expo-sqlite 在 React Native 中操作 SQLite

初始化数据库

首先,在你的项目中创建一个文件来管理数据库连接和操作,例如 Database.js。

// Database.js

import * as SQLite from 'expo-sqlite';

const db = SQLite.openDatabase('mydatabase.db');

export default db;

创建表

在应用启动时,可以创建所需的表。你可以在应用的入口文件(如 App.js)中执行初始化脚本。

// App.js

import React, { useEffect } from 'react';

import { View, Text, Alert } from 'react-native';

import db from './Database';

const App = () => {

useEffect(() => {

db.transaction(tx => {

tx.executeSql(

`CREATE TABLE IF NOT EXISTS users (

id INTEGER PRIMARY KEY AUTOINCREMENT,

username TEXT NOT NULL,

email TEXT NOT NULL UNIQUE

);`,

[],

() => console.log('Table created successfully'),

error => console.error('Error creating table', error)

);

});

return () => {}; // Cleanup if necessary

}, []);

return (

React Native SQLite Example

);

};

export default App;

插入数据

使用事务 (transaction) 来执行插入操作。

const addUser = (username, email) => {

db.transaction(tx => {

tx.executeSql(

`INSERT INTO users (username, email) VALUES (?, ?);`,

[username, email],

(_, result) => {

console.log('User inserted successfully with ID:', result.insertId);

Alert.alert('Success', `User ${username} added!`);

},

error => console.error('Error inserting user', error)

);

});

};

// 调用示例

// addUser('john_doe', 'john@example.com');

查询数据

查询数据同样在事务中进行,并通过回调函数处理结果。

const getUsers = () => {

db.transaction(tx => {

tx.executeSql(

`SELECT * FROM users;`,

[],

(tx, results) => {

const len = results.rows.length;

const users = [];

for (let i = 0; i < len; i++) {

users.push(results.rows.item(i));

}

console.log('Users:', users);

// 你可以在这里更新组件的状态来显示用户列表

},

error => console.error('Error fetching users', error)

);

});

};

// 调用示例

// getUsers();

更新数据

更新数据也通过事务和 executeSql 方法完成。

const updateUserEmail = (id, newEmail) => {

db.transaction(tx => {

tx.executeSql(

`UPDATE users SET email = ? WHERE id = ?;`,

[newEmail, id],

(_, result) => {

console.log('User updated successfully');

Alert.alert('Success', `User email updated!`);

},

error => console.error('Error updating user', error)

);

});

};

// 调用示例

// updateUserEmail(1, 'newemail@example.com');

删除数据

删除数据同样通过事务和 SQL 语句完成。

const deleteUser = (id) => {

db.transaction(tx => {

tx.executeSql(

`DELETE FROM users WHERE id = ?;`,

[id],

(_, result) => {

console.log('User deleted successfully');

Alert.alert('Success', `User deleted!`);

},

error => console.error('Error deleting user', error)

);

});

};

// 调用示例

// deleteUser(1);

完整示例

以下是一个完整的 React Native 组件示例,展示如何创建表、插入、查询、更新和删除用户数据。

// App.js

import React, { useState, useEffect } from 'react';

import { View, Text, TextInput, Button, FlatList, Alert, StyleSheet } from 'react-native';

import db from './Database';

const App = () => {

const [username, setUsername] = useState('');

const [email, setEmail] = useState('');

const [users, setUsers] = useState([]);

useEffect(() => {

// 创建表

db.transaction(tx => {

tx.executeSql(

`CREATE TABLE IF NOT EXISTS users (

id INTEGER PRIMARY KEY AUTOINCREMENT,

username TEXT NOT NULL,

email TEXT NOT NULL UNIQUE

);`

);

});

// 加载用户数据

loadUsers();

// 清理函数(可选)

return () => {};

}, []);

const loadUsers = () => {

db.transaction(tx => {

tx.executeSql(

`SELECT * FROM users;`,

[],

(tx, results) => {

const len = results.rows.length;

const loadedUsers = [];

for (let i = 0; i < len; i++) {

loadedUsers.push(results.rows.item(i));

}

setUsers(loadedUsers);

},

error => console.error('Error fetching users', error)

);

});

};

const addUser = () => {

if (!username || !email) {

Alert.alert('Error', 'Please enter both username and email');

return;

}

db.transaction(tx => {

tx.executeSql(

`INSERT INTO users (username, email) VALUES (?, ?);`,

[username, email],

(_, result) => {

console.log('User inserted successfully with ID:', result.insertId);

Alert.alert('Success', `User ${username} added!`);

// 重置输入

setUsername('');

setEmail('');

// 重新加载用户数据

loadUsers();

},

error => console.error('Error inserting user', error)

);

});

};

const deleteUser = (id) => {

db.transaction(tx => {

tx.executeSql(

`DELETE FROM users WHERE id = ?;`,

[id],

(_, result) => {

console.log('User deleted successfully');

Alert.alert('Success', `User deleted!`);

// 重新加载用户数据

loadUsers();

},

error => console.error('Error deleting user', error)

);

});

};

const renderItem = ({ item }) => (

{item.username}

{item.email}

相关推荐

[交流]175狮驼、女儿、地府、化生和龙宫组合求指教
28365365体育在线投注

[交流]175狮驼、女儿、地府、化生和龙宫组合求指教

📅 08-26 👁️ 2812
服装修改改吗(衣服修改的店铺一般叫什么名字)
365骑士版app下载

服装修改改吗(衣服修改的店铺一般叫什么名字)

📅 09-23 👁️ 788