I'm very new to C, and have been trying to fetch a result from mysql and store it as a variable to be called later. So far I've managed to connect to my database, fetch the result and print it to the terminal. But I have no idea how to now store it as a variable. Any help is greatly appreciated.
Here is what I have so far:
#include <mysql.h>
#include <stdio.h>
main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = ""; /* set me first */
char *database = "develop";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
if (mysql_query(conn, "SELECT * FROM action ")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
/* output table name */
printf("MySQL Data:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
Thanks,
Liam.
The same way you would store any variable in C. You've got the hard part down since you can output your information to the console. To store the variable, assign it. In C you declare the type, name, then your SQL statement. e.g.
#include <sys/time.h>
#include <stdio.h>
#include <mysql.h>
int main(char **args) {
MYSQL_RES *result;
MYSQL_ROW row;
MYSQL *connection, mysql;
int state;
Above is where the variables are declared. The part that says *result; is the PHP equivalent of $result
Below he's connecting to the database.
/* connect to the mySQL database at athens.imaginary.com */
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,
"athens.imaginary.com",
0, 0,
"db_test", 0, 0);
/* check for a connection error */
if( connection == NULL ) {
/* print the error message */
printf(mysql_error(&mysql));
return 1;
}
state = mysql_query(connection,
"SELECT test_id, test_val FROM test");
if( state != 0 ) {
printf(mysql_error(connection));
return 1;
}
/* must call mysql_store_result() before we can issue any
* other query calls
*/
Assign the result, print the array
result = mysql_store_result(connection);
printf("Rows: %d\n", mysql_num_rows(result));
/* process each row in the result set */
while( ( row = mysql_fetch_row(result)) != NULL ) {
printf("id: %s, val: %s\n",
(row[0] ? row[0] : "NULL"),
(row[1] ? row[1] : "NULL"));
}
/* free the result set */
mysql_free_result(result);
/* close the connection */
mysql_close(connection);
Close the connection PHP speak: $conn = null;
printf("Done.\n");
}
Added notes to this source: http://docstore.mik.ua/orelly/linux/sql/ch13_01.htm
Related
I want to integrate MySQL database into my C program.
Is there a possible way to do so ? What are the libraries that should be used ? (If it's possible)
The C API code is distributed with MySQL. It is included in the mysqlclient library and allows C programs to access a database.
Many of the clients in the MySQL source distribution are written in C. If you are looking for examples that demonstrate how to use the C API, take a look at these clients. You can find these in the clients directory in the MySQL source distribution.
Here is a small program that connects to a MySQL server and list all tables from the database:
#include <mysql.h>
#include <stdio.h>
int main(void) {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
/* Change me */
char *server = "localhost";
char *user = "root";
char *password = "PASSWORD";
char *database = "mysql";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
if (mysql_query(conn, "show tables")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
/* output table name */
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
return 0;
}
I am trying to use MYSQL_PLUGIN_DIR with mysql_options(). And on doing so my application crashes.
Here is simple code which crashes--
#include "stdafx.h"
#include <mysql.h>
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
#include <Windows.h>
#include<process.h>
MYSQL *conn; // the connection
MYSQL_RES *res; // the results
MYSQL_ROW row;
struct connection_details
{
char *server;
char *user;
char *password;
char *database;
};
MYSQL* mysql_connection_setup(struct connection_details mysql_details)
{
// first of all create a mysql instance and initialize the variables within
MYSQL *connection = mysql_init(NULL);
// connect to the database with the details attached.
if (!mysql_real_connect(connection,mysql_details.server, mysql_details.user, mysql_details.password, NULL, 0, NULL, 0)) {
printf("Conection error : %s\n", mysql_error(connection));
exit(1);
}
return connection;
}
MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query)
{
// send the query to the database
if (mysql_query(connection, sql_query))
{
printf("MySQL query error : %s\n", mysql_error(connection));
// exit(1);
}
return mysql_use_result(connection);
}
void mythread(void)
{
mysql_thread_init();
// assign the results return to the MYSQL_RES pointer
res = mysql_perform_query(conn,"select 2");
while ((row = mysql_fetch_row(res)) !=NULL)
printf("%s\n", row[0]);
/* clean up the database result set */
mysql_free_result(res);
/* clean up the database link */
}
void mythreadconnect(void)
{
struct connection_details mysqlD;
mysqlD.server = "localhost"; // where the mysql database is
mysqlD.user = "root"; // the root user of mysql
mysqlD.password = "root"; // the password of the root user in mysql
mysqlD.database = "myfirst"; // the databse to pick
//connect to mysql
conn = mysql_connection_setup(mysqlD);
}
int main()
{
char path[500]="C:\\Users\\abhishek\\Documents\\Visual Studio 2010\\Projects\\sampleapplication\\Debug\\";
mysql_library_init(0, NULL, NULL);
mysql_init(conn);
mysql_options(conn,MYSQL_PLUGIN_DIR ,path);
mythreadconnect();
mythread ();
mysql_library_end();
printf("Other business in Main\n");
printf("Main is exiting\n");
getch();
return 0;
}
It crashes at mysql_options(conn,MYSQL_PLUGIN_DIR ,path);. I have searched a lot but can't find solution. Please help what is wrong in this code. Thanks in advance.
Your mistake is with mysql_init. Use this conn = mysql_init( NULL );. In your case you have not allocated memory for conn and try to initialize. Read docs for mysql_init param and return value.
This is a C program that connects to a MySQL server and executes an SQL query from a text file having a single query, in linux platform.
Here, first a connection with database server is established.
Next a line
show tables
is read from Text file , named "text.txt"
This is stored in a string called, line. And this string is passed in to function mysql_query of MySQL C API. Then the MySQL database will return the result, that is name of tables using function mysql_use_result.
The above should be the correct working of this code.
But during passing of string,line (containing the data of file "text.txt") to mysql_query() there is some error.
ERROR:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '�����o���+N�J�O�Q�' at line 2
That means some garbage value is also passed with actual data in file through string, line.So how can I correct this.
CODE:
#include mysql.h
#include stdio.h
main()
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "1"; /* set me first */
char *database = "mysql";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/*reading query from text file*/
int fd,i=0;
char line[300];
char ch1;
FILE *fp;
fp =fopen("text.txt","r");
if(fp ==NULL )
{
printf("File open error.\n");
exit(-1);
}
ch1 = getc(fp);
while (ch1 != EOF)
{
line[i]=ch1;
ch1 = getc(fp);
i++;
}
printf("%s",line);
fclose(fp);
/* send SQL query */
if (mysql_query(conn,line )) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
/* output table name */
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
I get too many connections when I try to connect to MySQL.
Why did I get that error although I close the connection whenever I connect to the MySQL server?
How should I solve that problem?
UPDATE
I run this on Ubuntu. My project is CGI which is written with C.
My web server is Apache.
This is an example of my source Code. Others are almost the same.
#include <mysql.h>
#include <stdio.h>
#include <string.h>
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "jitcomm"; /* set me first */
char *database = "profile";
int main(int argc, char *argv[])
{
if(argc==1)
getAll();
else
getOneUser(argv[1]);
return 0;
}
// show user
void getAll()
{
char query[500];
char result[1024];
memset(result,0,1024);
memset(query,0,500);
conn = mysql_init(NULL);
int i;
FILE *fout;
if((fout = fopen("gUsers","w"))==NULL)
{
printf("error with file");
}
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
sprintf(query,"select * from userTbl");
if (mysql_query(conn, query))
{
fprintf(stderr, "%s\n", mysql_error(conn));
exit(2);
}
res = mysql_use_result(conn);
/* output table name */
system("clear");
sprintf(result,"ID\t Name\t Password\t Role\n");
while ((row = mysql_fetch_row(res)) != NULL)
{
//printf("%s \n", row[0]);
//strcpy(id,row[0]);
sprintf(query,"%s\t %s\t %s\t\t %s\n",row[0], row[1], row[2], row[3]);
strcat(result,query);
for(i = 1 ;i<4;i++)
{
if(i==1)
fprintf(fout,"%s\n",row[i]); //write data to the file
if(i==2)
fprintf(fout,"%s\n",row[i]); //write data to the file
if(i==3)
fprintf(fout,"%s\n",row[i]); //write data to the file
}
}
/* close connection */
mysql_free_result(res);
mysql_close(conn);
//printf(result);
}
void getOneUser(char *n)
{
char query[500];
char result[1024];
memset(result,0,1024);
memset(query,0,500);
conn = mysql_init(NULL);
int i;
FILE *fout;
if((fout = fopen("gUsers","w"))==NULL)
{
printf("error with file");
}
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
sprintf(query,"select * from userTbl where name = '%s'",n);
if (mysql_query(conn, query))
{
fprintf(stderr, "%s\n", mysql_error(conn));
exit(2);
}
res = mysql_use_result(conn);
/* output table name */
system("clear");
sprintf(result,"ID\t Name\t Password\t Role\n");
while ((row = mysql_fetch_row(res)) != NULL)
{
//printf("%s \n", row[0]);
// //strcpy(id,row[0]);
sprintf(query,"%s\t %s\t %s\t\t %s\n",row[0], row[1], row[2], row[3]);
strcat(result,query);
for(i = 1 ;i<4;i++)
{
if(i==1)
fprintf(fout,"%s\n",row[i]); //write data to the file
if(i==2)
fprintf(fout,"%s\n",row[i]); //write data to the file
if(i==3)
fprintf(fout,"%s\n",row[i]); //write data to the file
}
}
/* close connection */
mysql_free_result(res);
mysql_close(conn);
//printf(result);
}
Hi
I'm trying to connect MySql using C in my project and it's the first time I use C and MySql.
I try to save a user name, password and role in MySql. When I run the program like that it's ok.
#include <mysql.h>
#include <stdio.h>
main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "admin"; /* set me first */
char *database = "profile";
char query[500];
memset(query,0,500);
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
int i =2;
/* send SQL query */
char userName[45] ="hi";
char userPassword[45];
char role[45];
strcpy(userName,"koko");
strcpy(userPassword,"hi");
strcpy(role,"admin");
sprintf(query,"insert into userTbl(name,password,role) values (\'%s\',\'%s\',\'%s\'); ",userName,userPassword,role);
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(2);
}
/* close connection */
mysql_close(conn);
}
I can run it without any errors though there are some warnings.
But when i wrote this program by using function, I got this error when I compile it .
Access denied for user 'root'#'localhost' (using password: YES)
#include <mysql.h>
#include <stdio.h>
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "admin"; /* set me first */
char *database = "profile";
void saveUser(char * , char * ,char * );
void updateUser(char * , char * ,char * );
void showData();
main()
{
saveUser("kevin","hi","admin");
}
void saveUser(char *name, char *password,char *role)
{
char query[500];
memset(query,0,500);
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
int i =2;
/* send SQL query */
sprintf(query,"insert into userTbl(name,password,role) values (\'%s\',\'%s\',\'%s\'); ",name,password,role);
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(2);
}
res = mysql_use_result(conn);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
void updateUser(char *name, char *password,char *role)
{
char query[500];
memset(query,0,500);
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
printf("1234511\n");
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
int i =2;
/* send SQL query */
sprintf(query,"update userTbl set password=\'%s\',role=\'%s\' where name=\'%s\'; ",password,role,name);
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(2);
}
/* close connection */
mysql_close(conn);
}
void showData()
{
/* output table name */
system("clear");
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
}
Can anybody explain me where I went wrong and how can I correct it.
I use gcc to get the executable file and run it on command prompt.
Thanks in advance.
Kevin
i read your post it's not the problem with your code try to connect to mysql server with the parameters(username and password) using a mysql client software like mysql query browser or sql yog or phpmyadmin whatever.
i think you set your password to blank, so simply replace the line
saveUser("kevin","hi","admin");
to
saveUser("kevin","","admin");
also ensure that you are passing the parameters in correct case since ubuntu's behavior is case senstive
give it a try if it helps.
please check for your correct username and passwords. usually when you install mysql server it asks for password and user to be set. as you are using ubuntu you might be using lamp server so try to get the correct credentials
there only the problem is with your credentials
Hi both Simon and Devjosh , Thanks for you help. I found the problem._The global variable name password is the same with the parameter name password in saveUser function _. Thanks a lot and so sorry disturb you .
Kevin