您的位置:首页 > 数据库

关于SQLite的基本使用

2015-08-10 15:41 435 查看
//SQLite的基本使用-Prefix.pch

1.

//

// Prefix header

//

// The contents of this file are implicitly included at the beginning of every source file.

//

#ifdef __OBJC__

#import <Foundation/Foundation.h>

#endif

2.

// Prefix header

//

// The contents of this file are implicitly included at the beginning of every source file.

//

#import <Availability.h>

#ifndef __IPHONE_5_0

#warning "This project uses features only available in iOS SDK 5.0 and later."

#endif

#ifdef __OBJC__

#import <UIKit/UIKit.h>

#import <Foundation/Foundation.h>

#endif

生成SQL

#import <Foundation/Foundation.h>

int main(int argc,
const char * argv[])

{

@autoreleasepool {

NSMutableString *sql = [NSMutableString
string];

NSArray *names =
@[@"jack",
@"rose", @"jim",
@"jake"];

for (int i =
0; i<100; i++) {

int index =
arc4random()%names.count;

NSString *namePre = names[index];

NSString *name = [NSString
stringWithFormat:@"%@-%d", namePre,
arc4random()%100];

int age =
arc4random() % 100;

double score =
arc4random() % 100;

[sql appendFormat:@"insert into t_student (name, age, score) values('%@', %d, %f);\n", name, age, score];

}

///Users/mc/Desktop/素材images

///Users/aplle/Desktop/student.sql

[sql writeToFile:@"Users/mc/Desktop/student.sql"
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];

}

return 0;

}

*****************************

#import <Foundation/Foundation.h>

int main(int argc,
const char * argv[])
{

@autoreleasepool {

NSArray *names =
@[@"西门抽血",
@"西门抽筋",
@"西门抽风",
@"西门吹雪"];

NSMutableString *sql = [NSMutableString
string];

for (int i =
0; i<200; i++) {

int ID = i + 1;

int age = arc4random_uniform(20) +
20;

NSString *name = names[arc4random_uniform(names.count)];

name = [name stringByAppendingFormat:@"-%d",
arc4random_uniform(100)];

[sql appendFormat:@"insert into t_student (id, name, age) values (%d, '%@', %d);\n", ID, name, age];
}

[sql writeToFile:@"/Users/apple/Desktop/students.sql"
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];

NSLog(@"\n%@", sql);
}

return 0;
}

插入数据:更改删除查询--->>>>>>>>>
#import "IWViewController.h"

#import <sqlite3.h>

@interface IWViewController ()
{

sqlite3 *_db; // db代表着整个数据库,db是数据库实例
}
- (IBAction)insert;
- (IBAction)update;
- (IBAction)delete;
- (IBAction)query;

@end

@implementation IWViewController

- (void)viewDidLoad
{

[super viewDidLoad];

// 0.获得沙盒中的数据库文件名

NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"student.sqlite"];

// 1.创建(打开)数据库(如果数据库文件不存在,会自动创建)
int result = sqlite3_open(filename.UTF8String,
&_db);
if (result == SQLITE_OK) {
NSLog(@"成功打开数据库");

// 2.创表

const char *sql = "create table if not exists t_student
(id integer primary key autoincrement, name text, age integer);";
char *errorMesg = NULL;
int result = sqlite3_exec(_db, sql, NULL, NULL,
&errorMesg);
if (result == SQLITE_OK) {

NSLog(@"成功创建t_student表");
} else {
NSLog(@"创建t_student表失败:%s",
errorMesg);
}
} else {
NSLog(@"打开数据库失败");
}
}

- (IBAction)insert
{
for (int i = 0; i<30;
i++) {
NSString *name = [NSString stringWithFormat:@"Jack-%d", arc4random()%100];
int age = arc4random()%100;

NSString *sql = [NSString stringWithFormat:@"insert
into t_student (name, age) values('%@', %d);", name, age];

char *errorMesg = NULL;
int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL,
&errorMesg);
if (result == SQLITE_OK) {
NSLog(@"成功添加数据");
} else {
NSLog(@"添加数据失败:%s",
errorMesg);
}
}
}

- (IBAction)update
{

}

- (IBAction)delete
{

}

- (IBAction)query
{

// SQL注入漏洞

/**

登录功能

1.用户输入账号和密码

* 账号:123' or 1 = 1 or '' = '

* 密码:456654679

2.拿到用户输入的账号和密码去数据库查询(查询有没有这个用户名和密码)

select * from t_user where username = '123' and password = '456';

select * from t_user where username = '123' and password = '456';

*/

// 1.定义sql语句

const char *sql = "select id, name, age from t_student
where name = ?;";

// 2.定义一个stmt存放结果集
sqlite3_stmt *stmt = NULL;

// 3.检测SQL语句的合法性
int result = sqlite3_prepare_v2(_db, sql, -1,
&stmt, NULL);
if (result == SQLITE_OK) {
NSLog(@"查询语句是合法的");

// 设置占位符的内容
sqlite3_bind_text(stmt, 1, "jack", -1, NULL);

// 4.执行SQL语句,从结果集中取出数据

// int stepResult = sqlite3_step(stmt);
while (sqlite3_step(stmt) == SQLITE_ROW) { // 真的查询到一行数据
// 获得这行对应的数据

// 获得第0列的id
int sid = sqlite3_column_int(stmt, 0);

// 获得第1列的name
const unsigned char *sname = sqlite3_column_text(stmt, 1);

// 获得第2列的age
int sage = sqlite3_column_int(stmt, 2);

NSLog(@"%d %s %d", sid, sname, sage);
}
} else {
NSLog(@"查询语句非合法");
}
}

@end

2.*************************

#import "ViewController.h"

#import <sqlite3.h>

@interface
ViewController ()
- (IBAction)insert;
- (IBAction)update;
- (IBAction)delete;
- (IBAction)select;

// db就是数据库的象征,如果要进行CRUD,得操作db这个实例

@property (nonatomic,
assign) sqlite3 *db;

@end

@implementation HMViewController

- (void)viewDidLoad
{

[super
viewDidLoad];

//
获得数据库文件的路径

NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)
lastObject];

NSString *filename = [doc
stringByAppendingPathComponent:@"students.sqlite"];

//
将OC字符串
转成 C语言字符串

const char *cfilename = filename.UTF8String;

// 1.打开数据库(如果数据库文件不存在,sqlite3_open函数会自动创建数据库文件)

int result = sqlite3_open(cfilename, &_db);

if (result == SQLITE_OK) {
// 打开成功

NSLog(@"成功打开数据库");

// 2.创表

const
char *sql =
"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);";

char *erroMsg = NULL;
result =
sqlite3_exec(self.db, sql,
NULL, NULL, &erroMsg);

if (result == SQLITE_OK) {

NSLog(@"成功创表");
}
else {

// printf("创表失败--%s--%s-%d", erroMsg, __FILE__, __LINE__);

NSLog(@"创表失败--%s--%@-%d", erroMsg, [NSString
stringWithUTF8String:__FILE__], __LINE__);
}
}
else {

NSLog(@"打开数据库失败");
}
}

- (IBAction)insert {

for (int i =
0; i<20; i++) {

// 1.拼接SQL语句

NSString *name = [NSString
stringWithFormat:@"Jack-%d",
arc4random_uniform(100)];

int age = arc4random_uniform(20) +
30;

NSString *sql = [NSString
stringWithFormat:@"INSERT INTO t_student (name, age) VALUES ('%@', %d);", name, age];

// 2.执行SQL语句

char *erroMsg = NULL;

sqlite3_exec(self.db, sql.UTF8String,
NULL, NULL, &erroMsg);

if (erroMsg) {

NSLog(@"插入数据失败--%s", erroMsg);
}
else {

NSLog(@"成功插入数据");
}
}
}

- (IBAction)update {

}

- (IBAction)delete {

}

- (IBAction)select {

const
char *sql =
"SELECT id, name, age FROM t_student WHERE age <= 30;";

//
进行查询前的准备工作

// -1
代表系统会自动计算SQL语句的长度

// sqlite3_stmt:用来取数据

sqlite3_stmt *stmt =
NULL;

if (sqlite3_prepare_v2(self.db, sql, -1, &stmt,
NULL) == SQLITE_OK) {
// SQL语句没有问题

NSLog(@"查询语句没有问题");

//
每调一次sqlite3_step函数,stmt就会指向下一条记录

while (sqlite3_step(stmt) ==
SQLITE_ROW) { //
找到一条记录

// 取出数据

//
取出第0列字段的值(int类型的值)

int ID = sqlite3_column_int(stmt,
0);

//
取出第1列字段的值(tex类型的值)

const unsigned
char *name = sqlite3_column_text(stmt,
1);

//
取出第2列字段的值(int类型的值)

int age = sqlite3_column_int(stmt,
2);

NSLog(@"%d %s %d", ID, name, age);
}
}
else {

NSLog(@"查询语句有问题");
}
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: