"unable to include mysql.h" in C program [duplicate] - mysql

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to make #include <mysql.h> work?
I need to connect C and mysql
This is my program
#include <stdio.h>
#include <mysql.h>
#define host "localhost"
#define username "root"
#define password "viswa"
#define database "dbase"
MYSQL *conn;
int main()
{
MYSQL_RES *res_set;
MYSQL_ROW row;
conn = mysql_init(NULL);
if( conn == NULL )
{ `
printf("Failed to initate MySQL\n");
return 1;
}
if( ! mysql_real_connect(conn,host,username,password,database,0,NULL,0) )
{
printf( "Error connecting to database: %s\n", mysql_error(conn));
return 1;
}
unsigned int i;
mysql_query(conn,"SELECT name, email, password FROM users");
res_set = mysql_store_result(conn);
unsigned int numrows = mysql_num_rows(res_set);
unsigned int num_fields = mysql_num_fields(res_set);
while ((row = mysql_fetch_row(res_set)) != NULL)
{
for(i = 0; i < num_fields; i++)
{
printf("%s\t", row[i] ? row[i] : "NULL");
}
printf("\n");
}
mysql_close(conn);
return 0;
}
I got the error "unable to include mysql.h".
I am using windows 7, Turbo C, mysql and I downloaded mysql-connector-c-noinstall-6.0.2-win32-vs2005, but I don't know how to include it.

Wrong syntax. The #include is a C preprocessor directive, not a statement (so should not end with a semi-colon). You should use
#include <mysql.h>
and you may need instead to have
#include <mysql/mysql.h>
or to pass -I /some/dir options to your compiler (with /some/dir replaced by the directory containing the mysql.h header).
Likewise, your #define should very probably not be ended with a semi-colon, you may need
#define username "root"
#define password "viswa"
#define database "dbase"
I strongly suggest reading a good book on C programming. You may want to examine the preprocessed form of your source code; when using gcc you could invoke it as gcc -C -E
yoursource.c to get the preprocessed form.
I also strongly recommend enabling warnings and debugging info (e.g. gcc -Wall -g for GCC). Find out how your specific compiler should be used. Learn also how to use your debugger (e.g. gdb). Study also existing C programs (notably free software).
You should learn how to configure your compiler to use extra include directories, and to link extra libraries.
N.B. With a linux distribution, you'll just have to install the appropriate packages and perhaps use mysql_config inside our Makefile (of course you'll need appropriate compiler and linker flags), perhaps with lines like
CFLAGS += -g -Wall $(shell mysql_config --cflags)
LIBES += $(shell mysql_config --libs)
added to your Makefile.

Related

How do you get the stream associated with a thrust execution policy?

I want to be able to get the stream-id which is associated with an execution policy in thrust. I am trying to access this function.
I have tried this :
cudaStream_t stream = 0;
auto policy = thrust::cuda::par.on(stream);
cudaStream_t str = stream(policy);
but I am getting a compilation error :
stream.cu(7): error: expression preceding parentheses of apparent call must have (pointer-to-) function type
Could I get some ideas on how to do this?
"I am trying to access this function." Trying to directly use e.g. things in detail are part of the implementation and may change from one version to the next. To wit: the file you are referring to does not even exist in the the current thrust distributed with CUDA 10.
However, this seems to work for me:
$ cat t354.cu
#include <thrust/execution_policy.h>
#include <iostream>
#include <cstring>
int main(){
cudaStream_t mystream;
cudaStreamCreate(&mystream);
auto policy = thrust::cuda::par.on(mystream);
cudaStream_t str = stream(policy);
for (int i = 0; i < sizeof(cudaStream_t); i++)
if ( *(reinterpret_cast<unsigned char *>(&mystream)+i) != *(reinterpret_cast<unsigned char *>(&str)+i)) {std::cout << "mismatch" << std::endl; return -1;}
std::cout << "match" << std::endl;
}
$ nvcc -std=c++11 -o t354 t354.cu
$ cuda-memcheck ./t354
========= CUDA-MEMCHECK
match
========= ERROR SUMMARY: 0 errors
$

Using c to insert variables in mysql database

I am trying to insert variable calculated in my C program using mysql API . Despite trying all types of tricks( single quote , double quotes , query placeholder) I am not able to enter the data. The libraries used are:
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <math.h>
#include <my_global.h>
#include <mysql.h>
The relevant bits of code are
MYSQL *con = mysql_init(NULL);
if (mysql_real_connect(con, "localhost", "test", "test123",
"transport", 0, NULL, 0) == NULL)
{
finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO gps_points(vehicle_id,lat,lon,speed) VALUES(unit_id_dec,lat,lon,speed_float)"))
{
finish_with_error(con);
}
mysql_close(con);
I am getting the following error:
Unknown column 'unit_id_dec' in 'field list'
The compile options used are:
sudo gcc socketListen.c -o listenSock -lm `mysql_config --cflags --libs`
Any solutions?
To solve this error you will need either rewrite trigger and remove 'unit_id_dec' variable or alter table and add variable 'unit_id_dec'.
Here's link how to rewrite trigger.
I have researched and found that following solution is working :
char buf[1024] = {};
char query_string[] = {
"INSERT INTO gps_points(vehicle_id,lat,lon,speed) VALUES(%u,%.4f,%.4f,%.2f)"
};
sprintf(buf, query_string,unit_id_dec,lat,lon,speed_float);
if (mysql_query(con,buf))
{
finish_with_error(con);
}

How do I open a URL from C++?

how can I open a URL from my C++ program?
In ruby you can do
%x(open https://google.com)
What's the equivalent in C++? I wonder if there's a platform-independent solution. But if there isn't, I'd like the Unix/Mac better :)
Here's my code:
#include <stdio.h>
#include <string.h>
#include <fstream>
int main (int argc, char *argv[])
{
char url[1000] = "https://www.google.com";
std::fstream fs;
fs.open(url);
fs.close();
return 0;
}
Your question may mean two different things:
1.) Open a web page with a browser.
#include <windows.h>
#include <shellapi.h>
...
ShellExecute(0, 0, L"http://www.google.com", 0, 0 , SW_SHOW );
This should work, it opens the file with the associated program. Should open the browser, which is usually the default web browser.
2.) Get the code of a webpage and you will render it yourself or do some other thing. For this I recommend to read this or/and this.
I hope it's at least a little helpful.
EDIT: Did not notice, what you are asking for UNIX, this only work on Windows.
Use libcurl, here is a simple example.
EDIT: If this is about starting a web browser from C++, you can invoke a shell command with system on a POSIX system:
system("<mybrowser> http://google.com");
By replacing <mybrowser> with the browser you want to launch.
Here's an example in windows code using winsock.
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
string website_HTML;
locale local;
void get_Website(char *url );
int main ()
{
//open website
get_Website("www.google.com" );
//format website HTML
for (size_t i=0; i<website_HTML.length(); ++i)
website_HTML[i]= tolower(website_HTML[i],local);
//display HTML
cout <<website_HTML;
cout<<"\n\n";
return 0;
}
//***************************
void get_Website(char *url )
{
WSADATA wsaData;
SOCKET Socket;
SOCKADDR_IN SockAddr;
int lineCount=0;
int rowCount=0;
struct hostent *host;
char *get_http= new char[256];
memset(get_http,' ', sizeof(get_http) );
strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
strcat(get_http,url);
strcat(get_http,"\r\nConnection: close\r\n\r\n");
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{
cout << "WSAStartup failed.\n";
system("pause");
//return 1;
}
Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
host = gethostbyname(url);
SockAddr.sin_port=htons(80);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
cout << "Connecting to "<< url<<" ...\n";
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
{
cout << "Could not connect";
system("pause");
//return 1;
}
cout << "Connected.\n";
send(Socket,get_http, strlen(get_http),0 );
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
{
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r')
{
website_HTML+=buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();
delete[] get_http;
}
I was having the exact same problem in Windows.
I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:
'open' is not recognized as an internal or external command
After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.
Linux: xdg-open <URL>
Windows: start <URL>
For those of you that are using Windows, as I am, you can use the following:
std::string op = std::string("start ").append(url);
system(op.c_str());
I've had MUCH better luck using ShellExecuteA(). I've heard that there are a lot of security risks when you use "system()". This is what I came up with for my own code.
void SearchWeb( string word )
{
string base_URL = "http://www.bing.com/search?q=";
string search_URL = "dummy";
search_URL = base_URL + word;
cout << "Searching for: \"" << word << "\"\n";
ShellExecuteA(NULL, "open", search_URL.c_str(), NULL, NULL, SW_SHOWNORMAL);
}
p.s. Its using WinAPI if i'm correct. So its not multiplatform solution.
There're already answers for windows. In linux, I noticed open https://www.google.com always launch browser from shell, so you can try:
system("open https://your.domain/uri");
that's say
system(("open "s + url).c_str()); // c++
https://linux.die.net/man/1/open
C isn't as high-level as the scripting language you mention. But if you want to stay away from socket-based programming, try Curl. Curl is a great C library and has many features. I have used it for years and always recommend it. It also includes some stand alone programs for testing or shell use.
For linux environments, you can use xdg-open. It is installed by default on most distributions. The benefit over the accepted answer is that it opens the user's preferred browser.
$ xdg-open https://google.com
$ xdg-open steam://run/10
Of course you can wrap this in a system() call.
Create a function and copy the code using winsock which is mentioned already by Software_Developer.
For Instance:
#ifdef _WIN32
// this is required only for windows
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{
//...
}
#endif
winsock code here
#ifdef _WIN32
WSACleanup();
#endif

C code cant run select query in cron

We have a C code as below. This is how we have compiled it gcc -o get1Receive $(mysql_config --cflags) get1ReceiveSource.c $(mysql_config --libs) -lrt. I works fine when we run from the terminal. Then we tried to run it using cron job and when we review this two line printf("\nNumf of fields : %d",num_fields); and printf("\nNof of row : %lu",mysql_num_rows(localRes1));. The first line shows 4 as the value and second line never give any values and is always 0. We have took the same select query and run on the db and confirm there is value but it is just not delivering when running via cron job.The script is given executable permission too.
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <mysql.h>
#include <string.h>
int flag = 0;
int main () {
MYSQL *localConn;
MYSQL_RES *localRes1;
MYSQL_ROW localRow1;
char *server = "localhost";
char *user = "user1";
char *password = "*****";
char *database = "test1";
localConn = mysql_init(NULL);
if (!mysql_real_connect(localConn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(localConn));
exit(1);
}
struct timeval tv;
char queryBuf1[500],queryBuf2[500];
char buff1[20] = {0};
char buff2[20] = {0};
gettimeofday (&tv, NULL);
//fprintf (stderr, "[%d.%06d] Flag set to 1 on ", tv.tv_sec, tv.tv_usec);
//tv.tv_sec -= 5;
strftime(buff1, 20, "%Y-%m-%d %H:%M:00", localtime(&tv.tv_sec));
strftime(buff2, 20, "%Y-%m-%d %H:%M:59", localtime(&tv.tv_sec));
printf("\nTime from %s", buff1);
printf("\nTime to %s", buff2);
sprintf(queryBuf1,"SELECT ipDest, macDest,portDest, sum(totalBits) FROM dataReceive WHERE timeStampID between '%s' And '%s' GROUP BY ipDest, macDest, portDest ",buff1,buff2);
printf("\nQuery receive %s",queryBuf1);
if(mysql_query(localConn, queryBuf1))
{
printf("Error in first query of select %s\n",mysql_error(localConn));
exit(1);
}
localRes1 = mysql_store_result(localConn);
int num_fields = mysql_num_fields(localRes1);
printf("\nNumf of fields : %d",num_fields);
printf("\nNof of row : %lu",mysql_num_rows(localRes1));
while((localRow1 = mysql_fetch_row(localRes1)) !=NULL)
{
int totalBits = atoi(localRow1[3]);
printf("totalBits %d\n", totalBits);
printf("RECEIVE %s,%s\n", localRow1[0], localRow1[1]);
if(totalBits>5000)
{
sprintf(queryBuf1,"INSERT INTO alertReceive1 (timeStampID,ipDest, macDest, portDest, totalBits)VALUES ('%s','%s','%s','%s',%s)",buff1, localRow1[0],localRow1[1],localRow1[2],localRow1[3]);
printf("Query 1 before executing %s\n",queryBuf1);
if (mysql_real_query(localConn,queryBuf1,strlen(queryBuf1))) {
printf("Error in first insert %s\n",mysql_error(localConn));
fprintf(stderr, "%s\n", mysql_error(localConn));
exit(1);
}
//printf("Query 1 after executing %s\n",queryBuf1);*/
}
}
mysql_free_result(localRes1);
mysql_close(localConn);
}
We have run this command file get1Receive and resulting to
file get1Receive
get1Receive.c: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped
We have also run this command * * * * * set > /tmp/myvars and below is the results.
GROUPS=()
HOME=/root
HOSTNAME=capture
HOSTTYPE=x86_64
IFS='
'
LOGNAME=root
MACHTYPE=x86_64-redhat-linux-gnu
OPTERR=1
OPTIND=1
OSTYPE=linux-gnu
PATH=/usr/bin:/bin
POSIXLY_CORRECT=y
PPID=11086
PS4='+ '
PWD=/root
SHELL=/bin/sh
SHELLOPTS=braceexpand:hashall:interactive-comments:posix
SHLVL=1
TERM=dumb
UID=0
USER=root
_=/bin/sh
Generic hints (see also my comments):
Take time to read documentation notably from Advanced Linux Programming, man pages (which you can also get by typing man man or man 2 intro on the terminal, etc etc...), and MySQL 5.5 reference. Be sure to understand what GIYF or STFW means.
Put the \n at the end of printf format strings, not the beginning.
Also, call fflush(NULL) if appropriate, notably before any MySQL queries e.g. before your mysql_real_query calls, and at the end of your while loops
Compile with gcc -Wall -g e.g. with the following command in your terminal
gcc -Wall -g $(mysql_config --cflags) get1ReceiveSource.c \
$(mysql_config --libs) -lrt -o get1Receive
Improve the code till no warnings are given. (You may even want to have -Wall -Wextra instead of just -Wall). Don't forget to use a version control system like git.
use the gdb debugger (you need to learn how to use it).
(only once you are sure there is no more bugs in your code replace -g by -O2 -g in your compilation command)
use sizeof; most occurrences of 20 should be a sizeof, or at the very least use #define SMALLSIZE 20 and then only SMALLSIZE not 20.
Use snprintf not sprintf (and test its result size, which should fit!). snprintf(3) takes an extra size argument, e.g.
if (snprintf(querybuf, sizeof querybuf,
"SELECT ipDest, macDest, portDest, sum(totalBits)"
" FROM dataReceive"
" WHERE timeStampID between '%s' And '%s' "
" GROUP BY ipDest, macDest, portDest ",
buff1, buff2) >= (int) (sizeof querybuf))
abort();
consider using syslog(3) with openlog, and look into your system logs.
I don't see how is queryBuf1 declared. (Your code, as posted, probably don't even compile!). You might want something like char querybuf[512]; ...
And most importantly, calling mysql_real_query inside a mysql_fetch_row loop is wrong: you should have fetched all the rows before issuing the next MySQL query. Read more about MySQL C API.
You also forgot to test the result localRes1 of mysql_store_result(localConn); show somehow (perhaps thru syslog) the mysql_error(localConn) when localRes1 is NULL ....

How to use tcl apis in a c code

I want to use some of the functionalities(APIs) of my tcl code in another "c" code file. But i am not getting how to do that especiallly how to link them. For that i have taken a very simple tcl code which contains one API which adds two numbers and prints the sum. Can anybody tell me how can i call this tcl code to get the sum. How can i write a c wrapper that will call this tcl code. Below is my sample tcl program that i am using :
#!/usr/bin/env tclsh8.5
proc add_two_nos { } {
set a 10
set b 20
set c [expr { $a + $b } ]
puts " c is $c ......."
}
To evaluate a script from C code, use Tcl_Eval() or one of its close relatives. In order to use that API, you need to link in the Tcl library, initialize the Tcl library and create an interpreter to hold the execution context. Plus you really ought to do some work to retrieve the result and print it out (printing script errors out is particularly important, as that helps a lot with debugging!)
Thus, you get something like this:
#include <tcl.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
Tcl_Interp *interp;
int code;
char *result;
Tcl_FindExecutable(argv[0]);
interp = Tcl_CreateInterp();
code = Tcl_Eval(interp, "source myscript.tcl; add_two_nos");
/* Retrieve the result... */
result = Tcl_GetString(Tcl_GetObjResult(interp));
/* Check for error! If an error, message is result. */
if (code == TCL_ERROR) {
fprintf(stderr, "ERROR in script: %s\n", result);
exit(1);
}
/* Print (normal) result if non-empty; we'll skip handling encodings for now */
if (strlen(result)) {
printf("%s\n", result);
}
/* Clean up */
Tcl_DeleteInterp(interp);
exit(0);
}
I think i have sloved it out. You were correct. The problem was with the include method that i was using. I have the files tcl.h, tclDecls.h and tclPlatDecls.h included in the c code but these files were not existing in the path /usr/include so i was copying these files to that directory, may be it was not a proper way to do. Finally i have not copied those files to /usr/include and gave the include path while compiling. I have created executable and it is givingthe proper result on terminal. Thanks for your help.
Here is the exact c code i am using :
#include <tcl.h>
#include <tclDecls.h>
#include <tclPlatDecls.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv) {
Tcl_Interp *interp;
int code;
char *result;
printf("inside main function \n");
// Tcl_InitStubs(interp, "8.5", 0);
Tcl_FindExecutable(argv[0]);
interp = Tcl_CreateInterp();
code = Tcl_Eval(interp, "source simple_addition.tcl; add_two_nos");
/* Retrieve the result... */
result = Tcl_GetString(Tcl_GetObjResult(interp));
/* Check for error! If an error, message is result. */
if (code == TCL_ERROR) {
fprintf(stderr, "ERROR in script: %s\n", result);
exit(1);
}
/* Print (normal) result if non-empty; we'll skip handling encodings for now */
if (strlen(result)) {
printf("%s\n", result);
}
/* Clean up */
Tcl_DeleteInterp(interp);
exit(0);
}
And to compile this code and to generate executable file i am using below command :
gcc simple_addition_wrapper_new.c -I/usr/include/tcl8.5/ -ltcl8.5 -o simple_addition_op
I have executed the file simple_addition_op and got below result which was proper
inside main function
c is 30 .......
My special thanks to Donal Fellows and Johannes