将我的iPad应用程序连接到SQL Server

时间:2012-07-12 23:23:59

标签: ios sql-server xcode ipad

我有一个iPad应用程序,它使用表视图控制器来显示数据列表。我想将这些表连接到SQL Server中的数据。我对这个编程领域的经验很少,我不知道从哪里开始。从长远来看,我想在应用程序上添加/编辑/删除数据以与服务器同步。我知道这是一个非常广泛的问题,所以我主要是在寻找帮助我入门的建议。例如,我不想开始研究和学习核心数据,如果它不是可以实现我的目标的框架。

简而言之,我如何将我的应用程序连接到SQL Server,以便我可以访问其数据并将其同步到设备?任何示例代码/演练都将非常感激。

2 个答案:

答案 0 :(得分:1)

我目前正在使用需要相同功能的iOS应用程序。对于服务器上的mySQL数据库查询,我使用的服务器端PHP脚本可以接受变量,例如表名或数据库搜索项。

我做的是使用Objective-C的NSMutableURLRequest发出HTTP GET请求,然后让服务器处理请求(在PHP中),然后以JSON格式将数据库查询结果返回给我的应用程序。我使用SBJsonParser将返回的数据解析为NSData,然后解析NSArray对象。

在Objective-C中发出HTTP请求的示例:

NSString *urlString = [NSString stringWithFormat:@"http://website.com/yourPHPScript.php?yourVariable=something"];
NSURL *url = [NSURL URLWithString: urlString];

NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] initWithURL:url];

/* set the data and http method */  
[request1 setHTTPMethod:@"GET"];
[request1 setHTTPBody:nil];

/* Make the connection to the server with the http request */
[[NSURLConnection alloc] initWithRequest:request1 
                                delegate:self];

您需要添加更多代码才能在返回时实际响应请求,如果您愿意,我可以发布一个示例。

我实际上不知道这是否是最好的方法,但到目前为止它对我有用。它确实需要你知道PHP,如果你有任何经验,我不认识你。


更新:

以下是一些示例代码,说明如何响应请求。就我而言,由于我收到了JSON编码的响应,我使用SBJsonParser来解析响应。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    /* This string contains the response data.
     * At this point you can do whatever you want with it 
     */
    NSString *responseString = [[NSString alloc] initWithData:receivedData
                                                     encoding:NSUTF8StringEncoding];

    /* Here I parse the response JSON string into a native NSDictionary using an SBJsonParser */
    SBJsonParser *parser = [[[SBJsonParser alloc] init] autorelease];

    /* Parse the JSON into an NSDictionary */
    NSDictionary *responseArr = [parser objectWithString:responseString];

    /* Do whatever you want to do with the response */

    /* Relsease the connection unless you want to re-use it */
    [connection release];
}

同时添加这些方法,假设您有一个名为receivedData的NSMUtableData实例变量。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{ 
    [receivedData appendData:data];
}

答案 1 :(得分:0)

我不建议直接连接到SQL服务器。理论上,您可以尝试为iOS编译FreeTDS或unixODBC。我没有尝试过,但根据我的经验,至少FreeTDS应该是相当便携的。

然而,还有许多其他(并且为了大多数目的更好,更容易)与SQL Server同步数据的方式。例如,您可以在iPad端使用RestKit,在SQL Server端使用简单的REST服务。或者你可以使用OData iOS library(我最近才知道,我必须承认)。