my Dictionary output is-
i want to fire insert command to insert this dictionary data to the sqlite database
(
{
iCardReceiverName = rp;
iCardSenderName = madhusudan;
isDeleted = 0;
isReceiverSynk = 0;
},
{
iCardReceiverName = rp;
iCardSenderName = mmmm;
isDeleted = 0;
isReceiverSynk = 0;
}
)
i want to insert this data into sqlite database.
here is my code-
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
NSMutableString *query = [NSMutableString stringWithFormat:#"Insert into iCardUsers ("];
[self.dbManager executeQuery:query];
if (self.dbManager.affectedRows != 0) {
NSLog(#"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);
}
else{
NSLog(#"Could not execute the query.");
}
for (int i = 0; i<[[jsonData allKeys] count]; i++)
{
[query appendFormat:#"%#,",[[jsonData allKeys] objectAtIndex:i]];
}
[query appendFormat:#")values ("];
for (int i = 0; i<[[jsonData allKeys] count]; i++)
{
[query appendFormat:#"%#,",[jsonData valueForKey:[[jsonData allKeys] objectAtIndex:i]]];
}
[query appendFormat:#");"];
NSLog(#"qry : %#",query);
You can insert your data in sqlite db like in following example.
You can create a function with required parameters and insert data using the function.
-(void)InsertRecords:(NSMutableString *)txt{
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"movieData.sqlite"];
const char *dbpath = [dbPath UTF8String];
sqlite3 *contactDB;
sqlite3_stmt *statement;
NSLog(#"%#",dbPath);
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO myMovies (movieName) VALUES (\"%#\")", txt];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
sqlite3_bind_text(statement, 1, [txt UTF8String], -1, SQLITE_TRANSIENT);
} else {
NSLog(#"error");
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
Related
I need to create a c++ console application that query a site in turn to get the html page.
The site is static because when I queried it in the url I see the html file, so I use this code:
send(Socket, "GET /it/ricette/q-torte_forno_statico.html HTTP/1.1\r\nHost: worldrecipes.expo2015.org/\r\nConnection: close\r\n\r\n", strlen("GET /it/ricette/q-torte_forno_statico.html HTTP/1.1\r\nHost: worldrecipes.expo2015.org\r\nConnection: close\r\n\r\n"), 0);
char buffer[1000000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 1000000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
}
It doesn't give me any errors but don't show me the whole html page and every time that I call send the request I get different answers ... why?
This code below seems to only work on the index page worldrecipes.expo2015.org and not the sub pages. You might want to look at more advanced webbrowser controls for visual studio for parsing and processing HTML.
Like here : http://www.codeproject.com/Articles/3365/Embed-an-HTML-control-in-your-own-window-using-pla
here : https://msdn.microsoft.com/en-us/library/aa752046(v=vs.85).aspx
and here : http://www.codeproject.com/Articles/3919/Using-the-WebBrowser-control-simplified
Example code:
#include <windows.h>
#include <string>
#include <stdio.h>
using std::string;
#pragma comment(lib,"ws2_32.lib")
HINSTANCE hInst;
WSADATA wsaData;
void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename);
SOCKET connectToServer(char *szServerName, WORD portNum);
int getHeaderLength(char *content);
char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut);
int main()
{
const int bufLen = 1024;
char *szUrl = "http://worldrecipes.expo2015.org/it/ricette/q-torte_forno_statico.html";
long fileSize;
char *memBuffer, *headerBuffer;
FILE *fp;
memBuffer = headerBuffer = NULL;
if ( WSAStartup(0x101, &wsaData) != 0)
return -1;
memBuffer = readUrl2(szUrl, fileSize, &headerBuffer);
printf("returned from readUrl\n");
printf("data returned:\n%s", memBuffer);
if (fileSize != 0)
{
printf("Got some data\n");
fp = fopen("downloaded.file", "wb");
fwrite(memBuffer, 1, fileSize, fp);
fclose(fp);
// SetDlgItemText(hwndDlg, IDC_EDIT4, headerBuffer);
// SetDlgItemText(hwndDlg, IDC_EDIT5, memBuffer);
delete(memBuffer);
delete(headerBuffer);
}
WSACleanup();
return 0;
}
void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename)
{
string::size_type n;
string url = mUrl;
if (url.substr(0,7) == "http://")
url.erase(0,7);
if (url.substr(0,8) == "https://")
url.erase(0,8);
n = url.find('/');
if (n != string::npos)
{
serverName = url.substr(0,n);
filepath = url.substr(n);
n = filepath.rfind('/');
filename = filepath.substr(n+1);
}
else
{
serverName = url;
filepath = "/";
filename = "";
}
}
SOCKET connectToServer(char *szServerName, WORD portNum)
{
struct hostent *hp;
unsigned int addr;
struct sockaddr_in server;
SOCKET conn;
conn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (conn == INVALID_SOCKET)
return NULL;
if(inet_addr(szServerName)==INADDR_NONE)
{
hp=gethostbyname(szServerName);
}
else
{
addr=inet_addr(szServerName);
hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
}
if(hp==NULL)
{
closesocket(conn);
return NULL;
}
server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
server.sin_family=AF_INET;
server.sin_port=htons(portNum);
if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
{
closesocket(conn);
return NULL;
}
return conn;
}
int getHeaderLength(char *content)
{
const char *srchStr1 = "\r\n\r\n", *srchStr2 = "\n\r\n\r";
char *findPos;
int ofset = -1;
findPos = strstr(content, srchStr1);
if (findPos != NULL)
{
ofset = findPos - content;
ofset += strlen(srchStr1);
}
else
{
findPos = strstr(content, srchStr2);
if (findPos != NULL)
{
ofset = findPos - content;
ofset += strlen(srchStr2);
}
}
return ofset;
}
char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut)
{
const int bufSize = 512;
char readBuffer[bufSize], sendBuffer[bufSize], tmpBuffer[bufSize];
char *tmpResult=NULL, *result;
SOCKET conn;
string server, filepath, filename;
long totalBytesRead, thisReadSize, headerLen;
mParseUrl(szUrl, server, filepath, filename);
///////////// step 1, connect //////////////////////
conn = connectToServer((char*)server.c_str(), 80);
///////////// step 2, send GET request /////////////
sprintf(tmpBuffer, "GET %s HTTP/1.0", filepath.c_str());
strcpy(sendBuffer, tmpBuffer);
strcat(sendBuffer, "\r\n");
sprintf(tmpBuffer, "Host: %s", server.c_str());
strcat(sendBuffer, tmpBuffer);
strcat(sendBuffer, "\r\n");
strcat(sendBuffer, "\r\n");
send(conn, sendBuffer, strlen(sendBuffer), 0);
// SetWindowText(edit3Hwnd, sendBuffer);
printf("Buffer being sent:\n%s", sendBuffer);
///////////// step 3 - get received bytes ////////////////
// Receive until the peer closes the connection
totalBytesRead = 0;
while(1)
{
memset(readBuffer, 0, bufSize);
thisReadSize = recv (conn, readBuffer, bufSize, 0);
if ( thisReadSize <= 0 )
break;
tmpResult = (char*)realloc(tmpResult, thisReadSize+totalBytesRead);
memcpy(tmpResult+totalBytesRead, readBuffer, thisReadSize);
totalBytesRead += thisReadSize;
}
headerLen = getHeaderLength(tmpResult);
long contenLen = totalBytesRead-headerLen;
result = new char[contenLen+1];
memcpy(result, tmpResult+headerLen, contenLen);
result[contenLen] = 0x0;
char *myTmp;
myTmp = new char[headerLen+1];
strncpy(myTmp, tmpResult, headerLen);
myTmp[headerLen] = NULL;
delete(tmpResult);
*headerOut = myTmp;
bytesReturnedOut = contenLen;
closesocket(conn);
return(result);
}
I'm testing a wrapper library for the MySQL C API, and I'm trying to insert a row.
I've tested it in GDB, and the line (in my code) that faults appears as follows:
Breakpoint 1, cq_query (con=0x7fffffffe1c0,
query=0x6014a0 "INSERT INTO TaskType(state,parentID,displayName) VALUES(1,19,'boop')") at cqstatic.c:32
32 return mysql_query(con->con, query);
This query string is formatted correctly (I can paste it into the mysql command line, and it runs fine), so it would appear that something is wrong in the connection (con->con is of type void * cast to MYSQL *).
My other functions which do SELECT and UPDATE work fine. Only insert appears to be broken.
Here is my Test Code
#include <stdio.h>
#include <string.h>
#include <cquel.h>
int main(void)
{
struct dbconn con = cq_new_connection("myurl.tld",
"myuser", "mypasswd", "mydb");
cq_init(1024, 128);
char *fields[] = {
"state",
"parentID",
"displayName"
};
char *vals[] = {
"1",
"19",
"boop"
};
struct drow *row = cq_new_drow(3);
cq_drow_set(row, vals);
struct dlist *list = cq_new_dlist(3, fields, "");
cq_dlist_add(list, row);
cq_insert(con, "TaskType", list);
cq_free_dlist(list);
return 0;
}
Insert Function
int cq_insert(struct dbconn con, const char *table, const struct dlist *list)
{
int rc;
char *query, *columns, *values;
const char *fmt = "INSERT INTO %s(%s) VALUES(%s)";
if (table == NULL)
return 1;
if (list == NULL)
return 2;
query = calloc(CQ_QLEN, sizeof(char));
if (query == NULL)
return -1;
columns = calloc(CQ_QLEN/2, sizeof(char));
if (columns == NULL) {
free(query);
return -2;
}
values = calloc(CQ_QLEN/2, sizeof(char));
if (values == NULL) {
free(query);
free(columns);
return -3;
}
rc = cq_dlist_fields_to_utf8(&con, columns, CQ_QLEN/2, *list);
if (rc) {
free(query);
free(columns);
free(values);
return 100;
}
rc = cq_connect(&con);
if (rc) {
free(query);
free(columns);
free(values);
return 200;
}
for (struct drow *r = list->first; r != NULL; r = r->next) {
rc = cq_drow_to_utf8(&con, values, CQ_QLEN/2, *r);
if (rc)
break;
rc = snprintf(query, CQ_QLEN, fmt, table, columns, values);
if (CQ_QLEN <= (size_t) rc) {
rc = -4;
break;
}
rc = cq_query(&con, query);
if (rc) {
rc = 201;
break;
}
}
cq_close_connection(&con);
free(query);
free(columns);
free(values);
return rc;
}
And one of the important helper functions
int cq_fields_to_utf8(struct dbconn *con, char *buf, size_t buflen,
size_t fieldc, char * const *fieldnames, bool usequotes)
{
int rc = 0;
size_t num_left = fieldc, written = 0;
if (num_left == 0)
return 1;
char *temp = calloc(CQ_FMAXLEN+3, sizeof(char));
if (NULL == temp)
return -1;
char *field = calloc((CQ_FMAXLEN+3)*2+1, sizeof(char));
if (NULL == field) {
free(temp);
return -2;
}
/* prevent appending to buffer */
buf[0] = '\0';
cq_connect(con);
for (size_t i = 0; i < fieldc; ++i) {
bool escaped = fieldnames[i][0] == '\\';
const char *orig = escaped ? &fieldnames[i][1] : fieldnames[i];
const char *value;
bool isstr = false;
if (!escaped) {
mysql_real_escape_string(con->con, field, orig, strlen(orig));
value = field;
if (usequotes)
for (size_t j = 0; j < strlen(value); ++j) {
if (!isdigit(value[j])) {
isstr = true;
break;
}
}
} else {
value = orig;
}
const char *a = isstr ? "'" : "";
const char *c = --num_left > 0 ? "," : "";
written += snprintf(temp, CQ_FMAXLEN+3, "%s%s%s%s", a, value, a, c);
if (written >= buflen) {
rc = 2;
break;
}
strcat(buf, temp);
}
cq_close_connection(con);
free(field);
free(temp);
return rc;
}
used when setting up the query string.
Found my own issue. Blame the 10 minute rule.
I didn't look closely enough at cq_insert(), and it is making a double connection, closing the second one, leaving the first one lost, and the pointer pointing to freed memory, so segfault.
I am new in cocos2dx .. I have some doubts in json parsing . I have got messages from server .But I cant post messages to the server . here i paste the code of getmessages. Plz hel me to post messages.Thanks in Advance.
void ChatRoom::function()
{
std::vector<std::string> headers;
headers.push_back("Content-Type: application/json; charset=utf-8");
cocos2d::extension::CCHttpRequest * request = new cocos2d::extension::CCHttpRequest();
request->setUrl("url here");
const char* postData ="chatManagerRequestType=GET_MESSAGES_AFTER_CHAT_ENABLED";
request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpGet);
request->setResponseCallback(this, httpresponse_selector(ChatRoom::onHttpRequestCompleted));
request->setRequestData(postData, strlen(postData));
request->setHeaders(headers);
cocos2d::extension::CCHttpClient::getInstance()->send(request);
request->release();
}
void ChatRoom::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
cocos2d::extension::CCHttpResponse * response = (cocos2d::extension::CCHttpResponse *)data;
if (!response)
{
return;
} std::string command;
if (0 != strlen(response->getHttpRequest()->getTag()))
{
command = response->getHttpRequest()->getTag();
CCLog("%s completed", response->getHttpRequest()->getTag());
}
int statusCode = response->getResponseCode();
char statusString[64] = {};
sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
CCLog("response code: %d", statusCode);
if (!response->isSucceed())
{
CCLog("response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
return;
}
std::vector<char> * buffer = response->getResponseData();
char * concatenated = (char *) malloc(buffer->size() + 1);
std::string s2(buffer->begin(), buffer->end());
strcpy(concatenated, s2.c_str());
CCLOG("%s",s2.c_str());
CCArray *arry=new CCArray();
printf("Http Test, dump data: ");
std::string tstr;
for (unsigned int i = 0; i < buffer->size(); i++)
{
char s[10];
sprintf(s, "%c",(*buffer)[i]);
tstr += (*buffer)[i];
arry->addObject((CCObject*)s);
}
for (int i=0; i<9; i++) {
cocos2d::extension::Json * jsondd = cocos2d::extension::Json_create(concatenated);
cocos2d::extension::Json *json1 = cocos2d::extension::Json_getItem(jsondd, "chatValueList");
cocos2d::extension::Json *json2 = cocos2d::extension::Json_getItemAt (json1, 0);
cocos2d::extension::Json *json3 = cocos2d::extension::Json_getItem(json2,"message");
cocos2d::extension::Json *json31 = cocos2d::extension::Json_getItem(json2,"chatId");
cocos2d::extension::Json *json4= cocos2d::extension::Json_getItem(json2,"userValue");
cocos2d::extension::Json *json5= cocos2d::extension::Json_getItem(json4,"userName");
cocos2d::extension::Json *json6= cocos2d::extension::Json_getItem(json4,"emailId");
val1 = json5->valuestring;
val2 = json3->valuestring;
val3 = json31->valueint;
CCLOG("value:%s %s %d",val1.getCString(),val2.getCString(),val3);
}
}
First of all, to post data using http you have to use kHttpPost not kHttpGet. So if you just set the request type to CCHttpRequest::kHttpPost you will be able to send your post data to server.
Second, if you are not having trouble with json then don't mention it in the question title. It misleads the users.
First of all, I'm new to objective-c programming so I've probably made some mistakes in my code.
Here's what I've done : I've created a php file with some xml to get values from my MySQL database. Everything goes into a NSArray in objective-C. If I look at the log, everything works fine because it shows my arrays with every MySQL rows and columns like this:
2012-04-02 08:20:14.822 POS[64632:707] (
{
CPU = 0;
TPS = "(null)";
TVQ = "(null)";
consigne = 0;
coutantQuantiteRecue = 0;
description = "";
nom = "";
prixProduit = 0;
quantiteRecue = 0;
stock = 0;
},
{
CPU = 768;
TPS = "(null)";
TVQ = "(null)";
consigne = 0;
coutantQuantiteRecue = 0;
description = "";
nom = hhh;
prixProduit = 0;
quantiteRecue = 0;
stock = 0;
},
2012-04-02 08:20:14.836 POS[64632:707] The number of rows is:2
The problem is that the only thing I get in my TableView is { in each cell like this:
Here's my .h :
#interface InventoryManagement : NSObject<NSApplicationDelegate, NSTableViewDataSource>
{
IBOutlet NSTableView* inventoryTable;
NSArray* m_items;
}
-(int)numberOfRowsInTableView:(NSTableView *)inventoryTable;
-(id)tableView:(NSTableView *)inventoryTable objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex;
-(void)dealloc;
#property (retain) NSArray* m_items;
#end
And here's my .m file :
#implementation InventoryManagement
#synthesize m_items;
-(id)init
{
[super init];
NSInteger index = 0;
NSString *urlString = [NSString stringWithFormat:#"http://localhost:8888/php/getProducts.php?index=%d&", index];
m_items = [NSArray arrayWithContentsOfURL:[NSURL URLWithString: urlString]];
NSLog(#"%#", [m_items description]);
[m_items retain];
[inventoryTable reloadData];
return self;
}
-(int)numberOfRowsInTableView:(NSTableView *)inventoryTable
{
NSLog(#"The number of rows in fullResult is:%i", [m_items count]);
return [m_items count];
}
-(id)tableView:(NSTableView *)inventoryTable objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex
{
return [m_items objectAtIndex:rowIndex];
}
-(void)dealloc
{
[m_items release];
[super dealloc];
}
#end
My object is well-connected to dataSource and delegate of my TableView. I want those cells to be filled by my database values.
Take a look at Cocoa Bindings for future works. They are great.
Regarding your question: the problem is in the method
-(id)tableView:(NSTableView *)inventoryTable objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex
{
return [m_items objectAtIndex:rowIndex];
}
You are returning the whole object, that is:
{
CPU = 768;
TPS = "(null)";
TVQ = "(null)";
consigne = 0;
coutantQuantiteRecue = 0;
description = "";
nom = hhh;
prixProduit = 0;
quantiteRecue = 0;
stock = 0; }
which is a string.
You have to check the tableColumn variable and return only the right information: e.g. quantiteRecue, CPU, etc..
The best way to do this is to create a Model class in ObjectiveC which wraps a row of your db. Then your m_items array will contains your Model class, and you can return the right property without parsing every time the string...
Dear community. The code bellow compiled fine, start, but return empty array. Same code with same base return well. May somebody suggest something?
-(NSArray *) mysqlDirectQuery:(NSString *)query
{
// query doesn't using now
NSMutableArray *rows = [[NSMutableArray alloc] initWithCapacity:0];
MYSQL *sql = mysql_init( NULL );
//mysql_options(sql, MYSQL_READ_DEFAULT_GROUP, "LibMySQL");
sql = mysql_real_connect(sql, "localhost", "root", "", "test2", 3306, NULL, 0);
if (sql != NULL) {
mysql_query(sql, "select * from Users");
MYSQL_RES *qResult = mysql_store_result(sql);
if (qResult != NULL) {
MYSQL_ROW row;
while (row == mysql_fetch_row(qResult)) {
[rows addObject:[NSArray arrayWithObjects:
[NSString stringWithCString:row[0] encoding:NSISOLatin1StringEncoding],
nil]];
}
mysql_free_result(qResult);
}
mysql_close(sql);
mysql_server_end();
}
NSArray *resultArray = [NSArray arrayWithArray:rows];
rows = nil;
return resultArray;
}
Shouldn't this:
while (row == mysql_fetch_row(qResult))
be
while (row = mysql_fetch_row(qResult))
You are using row[0] below, but you are not assigning it.