gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:19:12 25 4
gpt4 key购买 nike

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

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

最佳答案

我目前正在使用需要相同功能的 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];
}

关于ios - 将我的 iPad 应用程序连接到 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11462158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com