用于在当前月份到下一个月将数据插入数据库的sql语句

时间:2016-08-09 07:19:19

标签: ios sqlite

如何在SQLite数据库中从当前月份到下个月2月插入批量数据。

我想将当前月份数据插入SQLite所有values (0,0,0)(?,?,?);

NSString *myString = [NSString stringWithFormat:@"insert into %@(\"month\", \"date\", \"time\") Values(?, ?, ?)",tableName];

我想从当前月份的开始日期到下一个3个月的数据插入到timesheetTable。

3 个答案:

答案 0 :(得分:1)

如果你想从另一个表中插入数据,可以试试这个

NSString *query = [NSString stringWithFormat:@"INSERT INTO %@(month,date,time) Values (SELECT month,date,time FROM timesheetTable WHERE dateFieldName between date('now','start of month') and date('now','start of month','+2 month')",tableName];

答案 1 :(得分:0)

试试这段代码:

NSString *myString = [NSString stringWithFormat:@"insert into %@(month, date, time) Values('%@', '%@', '%@')",tableName,month,date,time];

答案 2 :(得分:0)

我为你试了一个样品,我得到了解决方案。从当前日期到下一个两个月

NSCalendar *gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSInteger yearCurrent = [gregorian component:NSCalendarUnitYear fromDate:[NSDate date]];
NSLog(@"The year is: %ld", yearCurrent);

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *compo = [cal components:NSCalendarUnitMonth fromDate:[NSDate date]];
NSInteger month = compo.month;
NSLog(@"The month is: %ld", month);

NSDateComponents *compDay = [cal components:NSCalendarUnitDay fromDate:[NSDate date]];
NSInteger dateDay = compDay.day;
NSLog(@"The dateDay is: %ld",dateDay);


NSDate *firstDateOfMonth = [self getDateOfMonth:yearCurrent :month :dateDay];
NSDate *firstDateOfNextTwoMonth = [self getDateOfMonth:yearCurrent :month + 2 :dateDay];
NSDateComponents *component = [[NSCalendar currentCalendar] components:NSCalendarUnitDay fromDate:firstDateOfMonth toDate:firstDateOfNextTwoMonth options:0];
NSInteger totalDays = [component day];
NSLog(@"The total days are %ld", totalDays);


- (NSDate *)getDateOfMonth:(NSInteger)year:(NSInteger)month :(NSInteger)day
{
  NSDateComponents *dc = [[NSDateComponents alloc] init];
  dc.year = year;
  dc.month = month;
  dc.day = day;
  return [[NSCalendar currentCalendar] dateFromComponents:dc];
}

印刷结果

The year is: 2016
The month is: 8
The dateDay is: 9

最后总天数

The total days are 61

现在你没有总天数,所以在for循环中设置了

for(int i=0;i<totalDays;i++)
{
    //Do your stuff here......
    NSString *myString = [NSString stringWithFormat:@"insert into %@(month, date, time) Values(?, ?, ?)",tableName];
    sqlite3_stmt *stment=nil;
    if(sqlite3_prepare_v2(database,[strQuery UTF8String] , -1, &stment, NULL)==SQLITE_OK)
    {
       sqlite3_bind_text(stment, 1, [strMonth UTF8String], -1, SQLITE_TRANSIENT);
       sqlite3_bind_text(stment, 1, [strDate UTF8String], -1, SQLITE_TRANSIENT);
       sqlite3_bind_text(stment, 1, [strTime UTF8String], -1, SQLITE_TRANSIENT);
       sqlite3_step(stment);
       sqlite3_reset(stment);
    }        
}