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;
}
Related
I have tried to connect to mysql server from C code.
#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
main(){
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "12345"; /* set me first */
char *database = "mydatabase";
conn = mysql_init(NULL);
printf("done 1\n");
if (!mysql_real_connect(conn, server,
user, password, database, 3306, "/tmp/mysql.sock", 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
printf("done 2\n");
if (mysql_query(conn, "show tables")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
printf("done 3\n");
res = mysql_use_result(conn);
printf("done 4\n");
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
printf("done 5\n");
mysql_free_result(res);
mysql_close(conn);
}
But I have this weird problem:
done 1
Plugin caching_sha2_password could not be loaded: /usr//usr/lib/mysql/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory
I do not know why it tries to load lib from /usr//usr/
Please help if you have a deal with it already!
I have a short program written to try to connect to a MySQL database.
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
int main () {
MYSQL *conn;
char *server = "localhost";
char *user = "root";
char *password = "";
char *database = "database";
int port = 3306;
conn = mysql_init(NULL);
mysql_real_connect(conn, server,user,password,database, port, NULL, 0);
return 0;
}
It builds fine, but when I run it, the console reads
<terminated> (exit value: -1,073,741,515)
I don't think that is good, but I also have no idea what it means. Can anybody help me to decipher this?
This program worked for me against a fresh mysql 5.7 install with Ubuntu Linux.
#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>
int main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "<passwrd>"; /* 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);
}
/* 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);
}
Test
./a.out
MySQL Tables in mysql database:
columns_priv
db
engine_cost
event
func
general_log
gtid_executed
help_category
help_keyword
help_relation
help_topic
innodb_index_stats
innodb_table_stats
ndb_binlog_index
plugin
proc
procs_priv
proxies_priv
server_cost
servers
slave_master_info
slave_relay_log_info
slave_worker_info
slow_log
tables_priv
time_zone
time_zone_leap_second
time_zone_name
time_zone_transition
time_zone_transition_type
user
Please check that your mysql is running and accepting connections and that the program terminates properly. It might be easier to use the command-line to link your mysql.h (I did it with gcc main.c -lmysqlclient when I compiled the above).
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
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);
}
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