SQLite关系型数据库的使用
数据库(Database): 存放数据的仓库, 存放的是一张的表, 特别像Excel, Numbers, 都以表格的形式存放数据, 可以创建多张表。
常见的数据库: sqlite, MySQL, SQLServer, Oracle, Access。
使用数据库,主要是因为文件读写和归档读取数据需要一次把数据全部读出来, 占用内存开销大;其次是数据库数据效率高, 体现在增删改查。
数据库存储数据的步骤
1、新建一个数据库
2、新建一张表(table)
3、添加多个字段(column,列,属性)
4、添加多行记录(row,每行存放多个字段对应的值)
数据库的操作语句 (增删改查),即SQL(Structured Query Language)
SQL 语句不区分大小写, 字符串需要加""或''
常用语法:(主键: 是一条数据的唯一标示符, 一张表只能有一个主键, 主键不能够重复, 一般把主键名设为"id", 不需要赋值, 会自增;*代表所有的字段;where是条件)
1 表操作
(1)创建表: creat table 表名 (字段名字段数据类型 是否为主键, 字段名 字段数据类型, 字段名 字段数据类型...)
(2)修改表名:ALTER TABLE 旧表名 RENAME TO 新表名
(3)删除表:DROP TABLE 表名
(4)表添加一列:ALTER TABLE 表名 ADD COLUMN 列名数据类型 限定符
2 表数据操作
(1)查: select 字段名 (或者*) from 表名 where 字段名 = 值
(2)加: insert into 表名 (字段1, 字段2...) values (值1, 值2...)
(3)改: update 表名 set 字段 = 值 where 字段 = 值
(4)删: delete from 表名 where 字段 = 值
SQLite是一款轻型的嵌入式数据库,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就足够了。它的处理速度比Mysql、PostgreSQL这两款著名的数据库都还快。
SQLite名词解释
2个重要结构体
1 sqlite3 *pdb(数据库句柄,跟文件句柄FILE类似)
2 sqlite3_stmt *stmt(这个相当于ODBC的Command对象,用于保存编译好的SQL语句)
5个主要函数
1 sqlite3_open()(打开数据库)
2 sqlite3_exec()(执行非查询的sql语句)
3 sqlite3_prepare()(准备sql语句,执行select语句或者要使用parameterbind时,用这个函数(封装了sqlite3_exec))
4 Sqlite3_step()(在调用sqlite3_prepare后,使用这个函数在记录集中移动)
5 Sqlite3_close()(关闭数据库文件)
SQLite 存储类
1 NULL(值是一个 NULL 值)
2 INTEGER(值是一个带符号的整数,根据值的大小存储在1、2、3、4、6 或 8 字节中)
3 REAL(值是一个浮点值,存储为 8 字节的 IEEE 浮点数字)
4 TEXT (值是一个文本字符串,使用数据库编码(UTF-8、UTF-16BE 或 UTF-16LE)存储)
5 BLOB (值是一个 blob 数据,完全根据它的输入存储)
SQLite常用语句
1、打开数据库 sqlite3_open函数
2、预处理SQL语句sqlite3_prepare_v2函数
3、绑定参数sqlite3_bind_text函数
4、执行SQL语句sqlite3_step函数(状态:*SQLITE_BUSY-数据库被锁定、*SQLITE_DONE-成功执行过程、*SQLITE_ROW-返回一行结果、*SQLITE_ERROR-运行错误、*SQLITE_MISUSE-错误的使用了本函数)
5、提取字段数据sqlite3_column_text、sqlite3_column_blob、sqlite3_column_int等函数
6、释放statement对象资源 sqlite3_finalize函数
7、关闭数据库 sqlite3_close函数
SQLite的使用
1、在iOS中使用SQLite时,首先需要添加库文件libsqlite3.tbd
2、导入主头文件 #import
3、数据库操作(注:设置数据库名称及路径)
示例代码:
设置数据库路径
- (void)setSQLitePath
{
if (self.filePath == nil)
{
// document目录下
NSArray *documentArray =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *document = [documentArray objectAtIndex:0];
_filePath = [document stringByAppendingPathComponent:SQLiteFile];
}
NSLog(@"filePath %@", _filePath);
}
打开数据库,创建表
- (void)New
{
NSString *sql = @"CREATE TABLE IF NOT EXISTS STUDENT(NAME TEXTPRIMARY KEY, ADDRESS TEXT, PHONE TEXT)";
if (sql && 0 != sql.length)
{
[self setSQLitePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
{
// 打开数据库
sqlite3 *dataBase; // sqlite3
const char *fileName = [self.filePath UTF8String]; // [xxx UTF8String]是将NSString转换为C字符串,因为SQLite3是采用可移植的C(而不是 Objective-C)编写的,它不知道什么是NSString.
int openStatus = sqlite3_open(fileName, &dataBase);
if (openStatus != SQLITE_OK)
{
// 数据库打开失败,关闭数据库
sqlite3_close(dataBase);
NSAssert(0, @"打开数据库失败");
NSLog(@"打开数据库失败");
}
NSLog(@"打开数据库成功");
// 创建表
char *errorMsg;
const char *execSql = [sql UTF8String];
int execStatus = sqlite3_exec(dataBase,execSql, NULL, NULL, &errorMsg);
if (execStatus != SQLITE_OK)
{
// 创建表失败,关闭数据库
sqlite3_close(dataBase);
NSAssert1(0, @"创建表失败:%s",errorMsg);
}
NSLog(@"创建表成功");
}
}
}
插入数据
- (void)Insert
{
// ?号表示一个未定的值
NSString *sql = @"INSERT OR REPLACE INTO STUDENT (NAME, ADDRESS,PHONE) VALUES (?,?,?)";
if (sql && 0 != sql.length)
{
[self setSQLitePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
{
// 打开数据库
sqlite3 *dataBase; // sqlite3
const char *fileName = [self.filePath UTF8String];
int openStatus = sqlite3_open(fileName,&dataBase);
if (openStatus != SQLITE_OK)
{
// 数据库打开失败,关闭数据库
sqlite3_close(dataBase);
NSAssert(0, @"打开数据库失败");
NSLog(@"打开数据库失败");
}
NSLog(@"打开数据库成功");
const char *execSql = [sql UTF8String];
sqlite3_stmt *statment;
int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1,&statment, nil); // 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
if (execStatus == SQLITE_OK)
{
NSLog(@"插入更新表成功");
// 绑定参数开始
// 这里的数字1,2,3代表上面的第几个问号,这里将三个值绑定到三个绑定变量
sqlite3_bind_text(statment, 1,[@"zhangshaoyu" UTF8String], -1, NULL);
sqlite3_bind_text(statment, 2,[@"meizhou" UTF8String], -1, NULL);
sqlite3_bind_text(statment, 3,[@"13800138000" UTF8String], -1, NULL);
// 执行SQL语句 执行插入
if (sqlite3_step(statment) !=SQLITE_DONE)
{
NSAssert(NO, @"插入更新表失败。");
}
else
{
NSLog(@"插入更新表成功");
}
}
else
{
NSLog(@"插入更新表失败");
}
// 释放sqlite3_stmt对象资源
sqlite3_finalize(statment);
// 关闭数据库
sqlite3_close(dataBase);
}
}
}
修改更新数据
- (void)Update
{
NSString *sql = @"UPDATE STUDENT SET ADDRESS = ? where NAME =?";
if (sql && 0 != sql.length)
{
[self setSQLitePath];
if ([[NSFileManager defaultManager]fileExistsAtPath:self.filePath])
{
// 打开数据库
sqlite3 *dataBase; // sqlite3
const char *fileName = [self.filePath UTF8String];
int openStatus = sqlite3_open(fileName, &dataBase);
if (openStatus != SQLITE_OK)
{
// 数据库打开失败,关闭数据库
sqlite3_close(dataBase);
NSAssert(0, @"打开数据库失败");
NSLog(@"打开数据库失败");
}
NSLog(@"打开数据库成功");
const char *execSql = [sql UTF8String];
sqlite3_stmt *statment;
int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1,&statment, nil);
if (execStatus == SQLITE_OK)
{
NSLog(@"更新表成功");
// 绑定text类型的数据库数据
// 这里的数字1,2,3代表第几个问号。这里只有1个问号,这是一个相对比较简单的数据库操作,真正的项目中会远远比这个复杂
sqlite3_bind_text(statment, 1,[@"meizhouWUHUA" UTF8String], -1, NULL);
sqlite3_bind_text(statment, 2,[@"zhangshaoyu" UTF8String], -1, NULL);
// 执行插入
if (sqlite3_step(statment) !=SQLITE_DONE)
{
NSAssert(NO, @"更新表失败。");
}
else
{
NSLog(@"更新表成功");
}
}
else
{
NSLog(@"更新表失败");
}
// 释放sqlite3_stmt对象资源
sqlite3_finalize(statment);
// 关闭数据库
sqlite3_close(dataBase);
}
}
}
查找数据
- (void)Select
{
NSString *sql = @"SELECT * FROM STUDENT";
if (sql && 0 != sql.length)
{
[self setSQLitePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
{
// 打开数据库
sqlite3 *dataBase; // sqlite3
const char *fileName = [self.filePath UTF8String];
int openStatus = sqlite3_open(fileName, &dataBase);
if (openStatus != SQLITE_OK)
{
// 数据库打开失败,关闭数据库
sqlite3_close(dataBase);
NSAssert(0, @"打开数据库失败");
NSLog(@"打开数据库失败");
}
NSLog(@"打开数据库成功");
const char *execSql = [sql UTF8String];
sqlite3_stmt *statment;
int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1,&statment, nil);
if (execStatus == SQLITE_OK)
{
NSLog(@"查询成功");
// 查询成功,执行遍历操作
// 查询结果集中一条一条的遍历所有的记录,这里的数字对应的是列值,注意这里的列值,跟上面sqlite3_bind_text绑定的列值不一样!一定要分开,不然会crash,只有这一处的列号不同,注意!
while(sqlite3_step(statment) ==SQLITE_ROW)
{
const char *NAME = (char*)sqlite3_column_text(statment, 0);
if (NAME != NULL)
{
NSString *name =[[NSString alloc] initWithUTF8String:NAME];
NSLog(@"NAME%@", name);
}
char *ADDRESS = (char*)sqlite3_column_text(statment, 1);
if (ADDRESS != NULL)
{
NSString *address =[[NSString alloc] initWithUTF8String:ADDRESS];
NSLog(@"ADDRESS%@", address);
}
char *PHONE = (char*)sqlite3_column_text(statment, 2);
if (PHONE != NULL)
{
NSString *phone =[[NSString alloc] initWithUTF8String:PHONE];
NSLog(@"PHONE%@", phone);
}
}
}
else
{
NSLog(@"查询失败");
}
// 释放sqlite3_stmt对象资源
sqlite3_finalize(statment);
// 关闭数据库
sqlite3_close(dataBase);
}
}
}
删除数据
- (void)Delete
{
//NSString *sql = @"DELETE FROM STUDENT"; // 方法1
NSString *sql = @"DELETE FROM STUDENT where NAME = ?"; // 方法2
if (sql && 0 != sql.length)
{
[self setSQLitePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
{
// 打开数据库
sqlite3 *dataBase; // sqlite3
const char *fileName = [self.filePath UTF8String];
int openStatus = sqlite3_open(fileName,&dataBase);
if (openStatus != SQLITE_OK)
{
// 数据库打开失败,关闭数据库
sqlite3_close(dataBase);
NSAssert(0, @"打开数据库失败");
NSLog(@"打开数据库失败");
}
NSLog(@"打开数据库成功");
const char *execSql = [sql UTF8String];
sqlite3_stmt *statment;
int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1, &statment,nil);
if (execStatus == SQLITE_OK)
{
// 绑定text类型的数据库数据
// 这里的数字1,2,3代表第几个问号。这里只有1个问号,这是一个相对比较简单的数据库操作,真正的项目中会远远比这个复杂
sqlite3_bind_text(statment, 1,[@"zhangshaoyu" UTF8String], -1, NULL);
// 执行删除
if (sqlite3_step(statment) !=SQLITE_DONE)
{
NSAssert(NO, @"删除数据失败。");
NSLog(@"删除数据失败");
}
else
{
NSLog(@"删除数据成功");
}
}
else
{
NSLog(@"删除数据失败");
}
// 释放sqlite3_stmt对象资源
sqlite3_finalize(statment);
// 关闭数据库
sqlite3_close(dataBase);
}
}
}
删除表
- (void)DeleteTable
{
NSString *sql = @"DROP TABLE STUDENT";
if (sql && 0 != sql.length)
{
[self setSQLitePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
{
// 打开数据库
sqlite3 *dataBase; // sqlite3
const char *fileName = [self.filePath UTF8String];
int openStatus = sqlite3_open(fileName, &dataBase);
if (openStatus != SQLITE_OK)
{
// 数据库打开失败,关闭数据库
sqlite3_close(dataBase);
NSAssert(0, @"打开数据库失败");
NSLog(@"打开数据库失败");
}
NSLog(@"打开数据库成功");
const char *execSql = [sql UTF8String];
sqlite3_stmt *statment;
int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1,&statment, nil);
if (execStatus == SQLITE_OK)
{
// 执行删除
if (sqlite3_step(statment) !=SQLITE_DONE)
{
NSAssert(NO, @"删除表失败。");
NSLog(@"删除表失败");
}
else
{
NSLog(@"删除表成功");
}
}
else
{
NSLog(@"删除表失败");
}
// 释放sqlite3_stmt对象资源
sqlite3_finalize(statment);
// 关闭数据库
sqlite3_close(dataBase);
}
}
}
数据查看
注意事项:
1、由于sqlite3是基于C语言编写的,而不是纯粹的object-c,所以有关字符串,我们不能使用NSString,因为它不识别,所以只能用c语言的字符串,char*,好在Nsstring提供了转换的方法,那就是 UTF8String。如:
NSString*sql = @"DELETE FROM STUDENT where NAME = ?";
constchar *execSql = [sql UTF8String];
2、sql语句中,不确定值使用?符号。如:
NSString*sql = @"DELETE FROM STUDENT where NAME = ?";
3、提取查询数据函数中的数字表示sql语句中的第几列(0~N)。如:
表示第1列:constchar *NAME = (char *)sqlite3_column_text(statment, 0);
4、绑定数据时函数中的数字表示sql语句中的第几个值。如:
NSString*sql = @"INSERT OR REPLACE INTO STUDENT (NAME, ADDRESS, PHONE) VALUES(?,?,?)";
表示第1个值:sqlite3_bind_text(statment,1, [@"zhangshaoyu" UTF8String], -1, NULL);
表示第2个值:sqlite3_bind_text(statment,2, [@"meizhou" UTF8String], -1, NULL);
表示第3个值:sqlite3_bind_text(statment,3, [@"13510213244" UTF8String], -1, NULL);
5、创建表时,必须设置一个主键PRIMARY KEY。如:
NSString*sql = @"CREATE TABLE IF NOT EXISTS STUDENT(NAME TEXT PRIMARY KEY, ADDRESSTEXT, PHONE TEXT)";

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.