gpt4 book ai didi

ios - 通过RESTful WCF服务从iPhone应用程序访问SQL数据库

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

我创建了一个小项目,可以通过RESTful WCF服务从iPhone读取数据并将数据插入到SQL Server。

我已经使用以下方法成功读取了数据:

1-我创建了一个wcf Web服务,该服务从Sql server中读取带有表employees(firstname,lastname,salary)的数据:

"41.142.251.142/JsonWcfService/GetEmployees.svc/json/employees"

2-我在xcode 5.0.2中创建了一个新项目,并添加了一个文本字段(viewData.text)以显示由Web服务检索到的数据。
3-我在viewController.m中添加了以下指令:
    "#define WcfSeviceURL [NSURL URLWithString: @"41.142.251.142/JsonWcfService/GetEmployees.svc/json/employees"]"

3-在(void)viewDidLoad方法中,我实现了以下代码:
     - (void)viewDidLoad
{
[super viewDidLoad];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:WcfSeviceURL options:NSDataReadingUncached error:&error];

if(!error)
{
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];

NSMutableArray *array= [json objectForKey:@"GetAllEmployeesMethodResult"];

for(int i=0; i< array.count; i++)
{
NSDictionary *empInfo= [array objectAtIndex:i];

NSString *first = [empInfo objectForKey:@"firstname"];
NSString *last = [empInfo objectForKey:@"lastname"];
NSString *salary = [empInfo objectForKey:@"salary"];

//Take out whitespaces from String
NSString *firstname = [first
stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *lastname = [last
stringByReplacingOccurrencesOfString:@" " withString:@""];

viewData.text= [viewData.text stringByAppendingString:[NSString stringWithFormat:@"%@ %@ makes $%@.00 per year.\n",firstname,lastname,salary]];
}

}
}

检查以下链接: http://www.codeproject.com/Articles/405189/How-to-access-SQL-database-from-an-iPhone-app-Via

如前所述,我可以毫无问题地从iPhone读取数据。

因此,第二步是如何将数据从iPhone写入和插入sql服务器。
为此,我首先创建了在Web服务中插入数据的方法:

在WCF界面中:
    [OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/InsertEmployee/{id1}/{id2}/{id3}")]
bool InsertEmployeeMethod(string id1,string id2, string id3);

实施中:
      public bool InsertEmployeeMethod(string id1,string id2, string id3)
{

int success = 0;

using (SqlConnection conn = new SqlConnection("server=(local);database=EmpDB;Integrated Security=SSPI;"))
{
conn.Open();

decimal value= Decimal.Parse(id3);
string cmdStr = string.Format("INSERT INTO EmpInfo VALUES('{0}','{1}',{2})",id1,id2,value);
SqlCommand cmd = new SqlCommand(cmdStr, conn);
success = cmd.ExecuteNonQuery();

conn.Close();
}

return (success != 0 ? true : false);
}

因此,要测试此网络服务方法,请使用:
"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/myName/MylastName/6565"

为了从iPhone使用这种方法,我使用了以下方法:
我声明了Define指令:
"#define BaseWcfUrl [NSURL URLWithString: 
@"41.142.251.142/JsonWcfService/GetEmployees.svc/json/InsertEmployee/{id1}/{id2}/{id3}"]"

然后,我实现了与单击按钮相关的插入员工方法。
      -(void) insertEmployeeMethod

{

if(firstname.text.length && lastname.text.length && salary.text.length)

{

NSString *str = [BaseWcfUrl stringByAppendingFormat:@"InsertEmployee/%@/%@/%@",firstname.text,lastname.text,salary.text];

NSURL *WcfServiceURL = [NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:WcfServiceURL];

[request setHTTPMethod:@"POST"];

// connect to the web

NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// NSString *respStr = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];


NSError *error;

NSDictionary* json = [NSJSONSerialization

JSONObjectWithData:respData

options:NSJSONReadingMutableContainers

error:&error];



NSNumber *isSuccessNumber = (NSNumber*)[json objectForKey:@"InsertEmployeeMethodResult"];

//创建一些标签字段以显示状态
        status.text = (isSuccessNumber && [isSuccessNumber boolValue] == YES) ? [NSString stringWithFormat:@"Inserted %@, %@",firstname.text,lastname.text]:[NSString stringWithFormat:@"Failed to insert %@, %@",firstname.text,lastname.text];
}

}

但是这里的问题在以下指令中:
 NSString *str = [BaseWcfUrl stringByAppendingFormat:@"InsertEmployee/%@/%@/%@",firstname.text,lastname.text,salary.text];

总是系统在此行返回一条消息 '数据参数nil',知道firstname.text和lastname.text,salary都已填满,并且我可以用 NSLog(@"First Name :%@",firstname.text)...查看它们的值

你能帮忙吗?
提前致谢。

最佳答案

我认为NSURL的stringByAppendingFormat不会满足您的要求。

尝试这样的事情:

#define kBase_URL                @"41.142.251.142/JsonWcfService/GetEmployees.svc/json/%@"

#define kAuthAPI_InsertEmployee_URL [NSString stringWithFormat:kBase_URL, @"InsertEmployee/%@/%@/%@"]

//Setup session
NSError *error;
NSURL *requestURL = [NSURL URLWithString:[NSString stringWithFormat:kAuthAPI_InsertEmployee_URL,firstname.text,lastname.text,salary.text]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];

NSData *postData = [NSJSONSerialization dataWithJSONObject:profileData options:0 error:&error];
[request setHTTPBody:postData];

etc. etc.

关于ios - 通过RESTful WCF服务从iPhone应用程序访问SQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20927101/

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