he estado tratando de crear una base de datos sqlite programáticamente en el tiempo de ejecución. ¿Alguien puede decir cómo crearlo en iphone sdk?create sqlite db programmatically en iphone sdk
Respuesta
Simplemente llame a la función sqlite3_open, creará una base de datos si no existe ninguna base de datos en la ruta.
// generate databasePath programmatically
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
// your code here
}
realizar un comentario si necesita más ejemplo de código en este
-(void)viewDidLoad
{
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(@"if");
}
sqlite3_close(contactDB);
} else
{
NSLog(@"else");
}
}
[filemgr release];
}
-(IBAction)table
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
// if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(@"tables failed");
// status.text = @"Failed to create table";
}
sqlite3_close(contactDB);
}
else
{
NSLog(@"tables failed");
//status.text = @"Failed to open/create database";
}
}
[filemgr release];
}
importar en .m archivo #import
importación en .m sqlite3.h archivo import y añadir marco en el proyecto ur libsqlite3.0.dylib
primero crea la clase NSObject y la llamabas Base de datos. en .h clase
@interface database : NSObject
{
NSString *databasePath;
NSString *databaseName;
sqlite3 *myDatabase;
NSArray *documentPaths;
NSString *documentsDir;
}
// --- métodos iniciales -------
-(void)createDatabaseIfNeeded;
// --------------- --transporte método de búsqueda --------------------- //
-(void)pathFind;
// ------------- ---- escribir valor ---------------------- //
-(void)writeValueInSettings:(NSMutableArray *)arrayvalue;
// ------------------- ha podido recuperar el valor de la configuración del vector ------------ //
-(NSMutableArray *)fetchValue;
// ------------------- actualizar el valor --------------------- //
-(void)updateSetting:(NSArray *)arr;
.m clase de escritura
-(id)init
{
if((self=[super init]))
{
[self createDatabaseIfNeeded];
}
return self;
}
//-----------create database if needed method--------------//
-(void)createDatabaseIfNeeded
{
[self pathFind];
BOOL success;
NSFileManager *filemgr = [NSFileManager defaultManager];
success=[filemgr fileExistsAtPath:databasePath];
if (success)return;
NSLog(@"not success");
//Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[filemgr copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
// ---------------- ruta encontrar ----------------- //
-(void)pathFind
{
databaseName = @"accDataBase.DB";
// Get the path to the documents directory and append the databaseName
documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
}
// ------------------ escribir valor en la configuración ---------------- //
-(void)writeValueInSettings:(NSMutableArray *)arrayvalue
{
NSLog(@"%@",arrayvalue);
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
database *objectDatabase=[[database alloc]init];
NSString *stringvalue2=[objectDatabase countValue];
[objectDatabase release];
int intvalue1=[stringvalue2 intValue];
intvalue1=intvalue1+1;
NSLog(@"opened");
NSString *sql1;
sql1=[[NSString alloc] initWithFormat:@"insert into setting values('%i','%i','%i','%@','%i','%i','%@','%i','%i','%i','%i','%i','%i','%@');",intvalue1,
[[arrayvalue objectAtIndex:0] intValue],[[arrayvalue objectAtIndex:1] intValue],[arrayvalue objectAtIndex:2],[[arrayvalue objectAtIndex:3] intValue],[[arrayvalue objectAtIndex:4]intValue ],[arrayvalue objectAtIndex:5],[[arrayvalue objectAtIndex:6]intValue],[[arrayvalue objectAtIndex:7]intValue ],[[arrayvalue objectAtIndex:8] intValue],[[arrayvalue objectAtIndex:9] intValue],[[arrayvalue objectAtIndex:10]intValue ],[[arrayvalue objectAtIndex:11]intValue],[arrayvalue objectAtIndex:12]];
char *err1;
if (sqlite3_exec(myDatabase,[sql1 UTF8String],NULL,NULL,&err1)==SQLITE_OK)
{
NSLog(@"value inserted:");
}
[sql1 release];
sqlite3_close(myDatabase);
}
} // ------------ ------------- ha podido recuperar todo el valor //
-(NSMutableArray *)fetchValue
{
NSMutableArray *list=nil;
list=[[[NSMutableArray alloc]init] autorelease];
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSString *sql=[NSString stringWithFormat: @"select * from setting where primaryKey=1"];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(myDatabase, [sql UTF8String], -1,&statement, NULL)==SQLITE_OK)
{
if(sqlite3_step(statement)==SQLITE_ROW)
{
for(int i=0;i<=13;i++)
{
char *pass=(char*)sqlite3_column_text(statement,i);
NSString *msg=[[NSString alloc]initWithUTF8String:pass];
[list addObject:msg];
[msg release];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(myDatabase);
}
return list;
}
// ----- ----------- actualizar el método de tabla de configuración --------------- //
-(void)updateSetting:(NSArray *)arr
{
if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
{
NSLog(@"opened");
sqlite3_stmt *compiledStmt;
// NSLog(@"%@",arr);
NSString *sqlStmt=[NSString stringWithFormat:@"UPDATE setting SET ragular=%i,cycle=%i, flow='%@', hour=%i,minute=%i,formate='%@' ,tenminute=%i ,thirtyminute=%i,sixtymin=%i, twentymin=%i, fourtyfivemin=%i ,other='%@',formatemessage ='%@' WHERE primaryKey=%i;",[[arr objectAtIndex:0]intValue],[[arr objectAtIndex:1]intValue],[arr objectAtIndex:2],[[arr objectAtIndex:3]intValue],[[arr objectAtIndex:4]intValue],[arr objectAtIndex:5],[[arr objectAtIndex:6]intValue],[[arr objectAtIndex:7]intValue],[[arr objectAtIndex:8]intValue],[[arr objectAtIndex:9]intValue],[[arr objectAtIndex:10]intValue],[arr objectAtIndex:11],[arr objectAtIndex:12],1];
// NSLog(@"%@",sqlStmt);
if(sqlite3_prepare_v2(myDatabase, [sqlStmt UTF8String],-1,&compiledStmt, NULL)==SQLITE_OK)
{
NSLog(@"updateding......cycle");
}
sqlite3_step(compiledStmt);
sqlite3_close(myDatabase);
}
}
wow. gracias por la gran ayuda ... – ravinder521986
- 1. iPhone SDK - Agregue un UINavigationController Programmatically
- 2. C# create report programmatically
- 3. Información segura contenida en iPhone SQLite DB
- 4. programmatically create new table with ios-core data
- 5. Abrir la aplicación de calendario iphone programmatically
- 6. Python Berkeley DB/Sqlite
- 7. crear nueva sqlite Db
- 8. Mejores prácticas para SQLite DB y ContentProvider
- 9. imagen de disco de la base de datos sqlite malformada en el SDK de iPhone
- 10. Cómo crear correctamente CREATE INDEX con SQLite
- 11. Android MediaStore sqlite db location
- 12. Android SQLite DB Cuándo cerrar
- 13. en navigationbar en iPhone SDK
- 14. Create View using Linked Server db en SQL Server
- 15. Exportar sqlite db en la aplicación phonegap
- 16. PDF Manipulación en iPhone SDK
- 17. Número aleatorio en iphone sdk?
- 18. iPhone - "Open In" en SDK?
- 19. GameKit en iPhone SDK 3.0
- 20. Reproducir sonidos en iPhone SDK?
- 21. Xcode iPhone - Base SDK, diferencia Active SDK?
- 22. iphone - programmatically call navigation controller button
- 23. ¿Cómo abrir invocar MKAnnotationView programmatically? (iPhone, MapKit)
- 24. iPhone sdk, excepto MPMediaItemCollection?
- 25. iPhone SDK: EXC_BAD_ACCESS con CFRelease para ABAddressBookRef
- 26. ¿Cómo actualizar la actualización de la aplicación SQLite DB en el iPhone?
- 27. Lectura y escritura de imágenes en un SQLite DB para iPhone use
- 28. iPhone SQLite DB y recomendaciones de sincronización e interacción de bases de datos basadas en web
- 29. Implementando sqlite DB en la actualización de la aplicación de iPhone
- 30. Primer código de Entity Framework 4 - Impedir DB Drop/Create
cualquier tutorial sobre este tema, saurabh. Por favor, puede darnos las gracias –