我已經能夠連接到我的應用程序中的MySQL數據庫,並使用幾乎完全像PHP命令(mysql_real_connect(),mysql_query(),mysql_fetch_array()等)的C API。)和我很舒服,我只是不知道如何返回數據查詢。我是否使用數組或字典,然後如何解析它?例如,在PHP中,我會這樣做(連接後):Objective-C和MySQL
$results = mysql_query("SELECT * FROM theDatabase");
if (mysql_num_rows($results) > 0) {
while($row = mysql_fetch_array($results)) {
print $row;
}
}
這個objective-c等價物是什麼?謝謝。
編輯:
OK,所以我取得了一些進步 - 我可以查詢並獲取字段數/行返回,似乎無法訪問數據本身。這裏是我的代碼,我從MySQL文檔和其他幾個網站上拼接在一起:
- (IBAction)dbConnect:(id)sender {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
MYSQL mysql;
mysql_init(&mysql);
if (!mysql_real_connect(&mysql, "10.1.1.99", "******", "******", "oldphotoarchive", 0, NULL, 0)) {
NSLog(@"%@", [NSString stringWithUTF8String:mysql_error(&mysql)]);
} else {
MYSQL_RES *result;
MYSQL_ROW row;
unsigned int num_fields;
unsigned int num_rows;
unsigned long *lengths;
if (mysql_query(&mysql,"SELECT * FROM photorecord")) {
// error
} else { // query succeeded, process any data returned by it
result = mysql_store_result(&mysql);
if (result) {
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result))) {
lengths = mysql_fetch_lengths(result);
for(int i = 0; i < num_fields; i++) {
//the line below is my problem, printing row[i] fails, I get the GNU gdb error...
row[i] ? NSLog(@"%@", row[i]) : NSLog(@"wtf");
}
}
} else {// mysql_store_result() returned nothing; should it have?
if (mysql_errno(&mysql)) {
NSLog(@ "Error: %s\n", mysql_error(&mysql));
} else if (mysql_field_count(&mysql) == 0) {
// query does not return data
// (it was not a SELECT)
num_rows = mysql_affected_rows(&mysql);
}
}
}
}
[pool release];
}