I try to execute following code using gcc test.c -o test.o -ldbi command.
#include <stdio.h>
#include <dbi/dbi.h>
int main() {
dbi_conn conn;
dbi_result result;
double threshold = 4.333333;
unsigned int idnumber;
const char *fullname;
dbi_initialize(NULL);
conn = dbi_conn_new("mysql");
dbi_conn_set_option(conn, "host", "localhost");
dbi_conn_set_option(conn, "username", "root");
dbi_conn_set_option(conn, "password", "root123");
dbi_conn_set_option(conn, "dbname", "test");
dbi_conn_set_option(conn, "encoding", "UTF-8");
if (dbi_conn_connect(conn) < 0) {
printf("Could not connect. Please check the option settings\n");
}
else {
result = dbi_conn_queryf(conn, "SELECT id, name FROM users");
if (result) {
while (dbi_result_next_row(result)) {
idnumber = dbi_result_get_uint(result, "id");
fullname = dbi_result_get_string(result, "name");
printf("%i. %s\n", idnumber, fullname);
}
dbi_result_free(result);
}
dbi_conn_close(conn);
}
dbi_shutdown();
return 0;
}
I have only 'Could not connect. Please check the option settings' as result always.
I can connect my data base using following command with password root123
mysql -h localhost -u root -p
And I can used test database in command line.
Please help me. What are the possible issues?
It has worked after install libdbd-mysql. Now I had install following packages.
libdbd-mysql
libdbi0
libdbi0-dev
Thank all of you.
Related
I don't usually code using C programming language but I learned it in school (so please bear with me because I am still a newbie).
In short, I was recently assigned to write code in C in order to delete rows from a table in MySQL database.
I used stackoverflow and other resources to help me with this code!
This is my code (not all of it):
void delete_rows(MYSQL *con)
{
char selection_query[256];
char deletion_query[256];
sprintf(selection_query, "SELECT id FROM <table> WHERE status = 'PROCESSING'\
AND started < DATE(NOW()) - INTERVAL %d DAY", expire_processing_days);
if (mysql_query(con, selection_query))
{
finish_with_error(con);
}
MYSQL_RES *result = mysql_store_result(con);
if (result == NULL)
{
finish_with_error(con);
}
int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
while ((row = mysql_fetch_row(result)))
{
for(int i = 0; i < num_fields; i++)
{
printf("Deleting process with id: %s ", row[i] ? row[i] : "NULL");
sprintf(deletion_query, "DELETE FROM <table> WHERE id = %d", row[i]);
if (mysql_query(con, deletion_query))
{
finish_with_error(con);
}
mysql_commit(con);
}
printf("\n");
}
mysql_free_result(result);
}
int main()
{
MYSQL *con;
DB_CONN_PARAMS *params = calloc(1,sizeof(DB_CONN_PARAMS));
//just an alternative way of passing connection params, find a struct easier
strcpy(params->host, <host>);
strcpy(params->user, <user>);
strcpy(params->pass, <password>);
strcpy(params->db, <database>);
MYSQL * connect_db(DB_CONN_PARAMS *params);
con = connect_db(params);
//we don't need the struct anymore
free(params);
params = NULL;
//kill processes that are incomplete/hanging
delete_rows(con);
//close mysql connection
mysql_close(con);
return EXIT_SUCCESS;
}
So, the code above compiles and runs without any errors, it prints out the ids of the rows that I want to delete. But when I go to the database to check the rows, they are still there!
Is there anything I am missing?
Ok, I have figured it out finally!
I changed the %d to %s in the following line:
sprintf(deletion_query, "DELETE FROM WHERE id = %d", row[i]);.
Because row[i] is a string, I was blind to that.
I was able to figure it out by printing the whole MySQL command and noticed that the id passed is wrong!
Thank you everyone for your attempts to help me.
I need to update a record in a MySQL table with Arduino UNO. I want to send data from HC-SR06 sensor to db. Firstly I need to see whether a record is updated or not. I am using Ethernet shield and Arduino UNO.
Here is my Arduino source code:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 177};
EthernetServer server(80);
String txData ="";
String wname = "sensor1";
void setup()
{
Serial.begin(9600);
Ethernet.begin(mac, ip);
server.begin();
}
void loop()
{
txData = "name="+ wname;
EthernetClient client = server.available();
if (client) {
delay (1000);
Serial.println(" client is ok-->");
boolean current_line_is_blank = true;
while (client.connected())
{
delay (1000);
Serial.println(" client connected-->");
if (client.available())
{
delay (1000);
Serial.println(" client available-->");
Serial.println("Connected to MySQL server. Sending data...");
client.print("POST /update_data.php HTTP/1.1\n");
client.print("Host: 192.168.1.177:80\n");
client.print("Connection: close\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(txData.length());
client.print("\n\n");
client.print(txData);
Serial.println("Successfull");
delay (1000);
}
}
delay(1);
client.stop();
}
}
Here is the update_data.php file:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
echo "dbconnect.php will run";
// Connect to MySQL
include("dbconnect.php");
// Prepare the SQL statement
$query = "update arduino.sensors SET value=1
where name = '$_POST[name]' ";
// Go to the review_data.php (optional)
//header("Location: review_data.php");
if(!#mysql_query($query))
{
echo "&Answer; SQL Error - ".mysql_error();
return;
mysql_close();
}
?>
Here is the dbconnect.php file:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$Username = "root"; // enter your username for mysql
$Password = "1234"; // enter your password for mysql
$Hostname = "localhost"; // this is usually "localhost" unless your database resides on a different server
$Database = "arduino"; //database name
$dbh = mysql_connect($Hostname , $Username, $Password) or die (mysql_error());;
if (!$dbh){
die('MySQL ERROR: ' . mysql_error());
}
#mysql_select_db($Database) or die ('MySQL Error:'.mysql_error());
?>
Client is started and I see the logs on browser like this, bu sensor1 record is not updated.
name=sensor1POST /update_data.php HTTP/1.1
Host: 192.168.1.177:80
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 12
You are literally sending:
update arduino.sensors SET value=1
where name = '$_POST[name]'
to the database. Unless you have a sensor called $_POST[name] nothing will happen!
You need to send the value of variable $_POST[name] as a parameter. I suggest you research Prepared Statements, as building a query by concatenating strings is open to SQL injection attacks.
I'm trying to build a C-program to add data to my MYSQL database and I would like to use variables within the SQL string. I want to insert UNIX time (epoch) in one column and the result from an energy meter into the other (double)
Even though it builds without errors or warnings I can't get it to insert the data into the table. Can someone give me a hint of where to look?
Thankful for all help I can get as I'm pretty much fumbling in the dark
Regards,
Mikael
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <mysql.h>
#include <my_global.h>
#include <stdlib.h> // For exit function
int loggingok; // Global var indicating logging on or off
double result = 323.234567; //Debug
double actual_time_sec;
void calculate_watts(void)
{
MYSQL *conn = mysql_init(NULL);
char *server = "localhost";
char *user = "root";
char *password = "password"; /* set me first */
char *database = "power";
char SQL_String[100];
char time_char[11];
char result_char[11];
time_t actual_time;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0);
sprintf(time_char,"%g",actual_time_sec);
sprintf(result_char,"%g",result);
printf("Tid: %g\n",actual_time_sec); //Debug
printf("Resultat: %g\n", result); //Debug
strcpy(SQL_String, "INSERT INTO consumption(time,consumption) VALUES(");
strcat(SQL_String, time_char);
strcat(SQL_String, ",");
strcat(SQL_String, result_char);
strcat(SQL_String, ")");
printf("SQL: %s", SQL_String); //Debug
// SQL_String = "INSERT INTO consumption(time,consumption) VALUES('"+ actual_time_sec +"',"+ result +")";
if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1); }
if (mysql_query(conn, SQL_String)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1); }
}
int main (int argc, char *argv[])
{
printf(argv[1]); //Debug
if(strcmp(argv[1], "db")) {
loggingok=1;
printf("Efergy E2 Classic decode \n\n");
calculate_watts(); }
else {
loggingok=0; }
return 0;
}
here is a great example...
http://php.net/mysql_query. Note the usage of sprintf here. The 2nd and 3rd parameters work with the sprintf to place the data in these 2 parameters exactly where they are needed in the SQL statement.
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
Please note the usage of if (!$result) this allows you to do a quick validation of if you have success or not. If an error is found the text resturned from mysql_error is placed in the message variable and then presented when the app dies.
me again with a little question about G-WAN and MySQL.
This script below works fine ...
My only problem is when MySQL went down. G-WAN script crash and G-WAN as well.
What is the nest way to keep a persistent MySQL connexion and handle MySQL downtime?
typedef struct {
MYSQL *conn;
} data_t;
int main(int argc, char *argv[])
{
u64 start = getus();
data_t **data = (data_t**)get_env(argv, US_SERVER_DATA);
xbuf_t *reply = get_reply(argv);
if(!data[0]) // first time: persistent pointer is uninitialized
{
data[0] = (data_t*)calloc(1, sizeof(data_t));
if(!data[0])
return 500; // out of memory
data[0]->conn = (MYSQL *)mysql_init(data[0]->conn);
if(! data[0]->conn) {
xbuf_xcat(reply, "MySQL Error");
return(200);
}
if(! mysql_real_connect(data[0]->conn, "localhost", "root", "willow", "test", NULL, NULL, 0)) {
return 500;
}
xbuf_cat(reply, "initialized data<br>");
}
// Do what we want here ...
Here my working script :
#pragma link "/usr/lib64/mysql/libmysqlclient.so"
#pragma include "/usr/include/mysql"
#include <mysql.h>
#include <string.h>
#include "gwan.h" // G-WAN exported functions
//static MYSQL *conn = NULL;
typedef struct {
MYSQL *conn;
} data_t;
int main(int argc, char *argv[])
{
u64 start = getus();
data_t **data = (data_t**)get_env(argv, US_SERVER_DATA);
xbuf_t *reply = get_reply(argv);
my_bool my_true = true;
if(!data[0]) // first time: persistent pointer is uninitialized
{
data[0] = (data_t*)calloc(1, sizeof(data_t));
if(!data[0])
return 500; // out of memory
data[0]->conn = (MYSQL *)mysql_init(data[0]->conn);
mysql_options(data[0]->conn, MYSQL_OPT_RECONNECT, &my_true);
if(! data[0]->conn) {
xbuf_xcat(reply, "MySQL Error");
return(200);
}
if(! mysql_real_connect(data[0]->conn, "localhost", "root", "willow", "test", 0, NULL, 0)) {
return 500;
}
xbuf_cat(reply, "initialized data<br>");
}
if(mysql_ping(data[0]->conn) > 0) return 500; // Prevent G-WAN to crash
mysql_query(data[0]->conn, "DELETE FROM example");
for(int i =1; i< 10; i++) {
char sql[1024];
s_snprintf(sql, 1023, "INSERT INTO example (id, name, age) VALUES(%d, 'Olivier', 33)", i);
mysql_query(data[0]->conn, sql);
}
int count = 0;
// Query Database
mysql_query(data[0]->conn, "SELECT id, name, age FROM example");
MYSQL_RES *result = mysql_store_result(data[0]->conn);
MYSQL_ROW *row;
while ((row = mysql_fetch_row(result))) {
count++;
xbuf_xcat(reply, ": %s : %s : %s", row[0], row[1], row[2]);
xbuf_xcat(reply, "<br/>");
}
mysql_free_result(result);
xbuf_xcat(reply, "<br>%llUmicro seconds : %d<br/>", (getus()-start), mysql_field_count(data[0]->conn));
xbuf_xcat(reply, "MySQL Client Version: %d", mysql_get_client_version());
return 200;
}
So now even when mysql is down, G-WAN is still alive, and the script works again when mysql is UP. Hope it will help someone else.
It be great if You do a bit of research before asking a question...
See -> http://dev.mysql.com/doc/refman/5.5/en/mysql-ping.html
when MySQL went down. G-WAN script crash and G-WAN as well
Since you only publish the code that creates the persistent connection to MySQL (and not the code that uses MySQL later), there's no way to see how your code manages to crash G-WAN.
But it is most likely that this is the MySQL driver library that is crashing when you are trying to use an invalid socket.
The solution here is obviously to test the validity of the socket (its connected state) via something like:
ioctl(fd,FIONREAD,&bytes_available);
...before you pass it to the MySQL client library.
I am using Java and Mysql for a Program, I am Using a Script File in order to restore a Databsae.
Under Java I am Executing a command:under bin: mysql -u root -proot test< c:\test.mysql
It is not running while If I run it under cmd line it will execute properly and restore the database.
Is anybody there who knows.. why it happens..
Whats the problem, why its not running if i run it under Java environment.
EXACT SYNTAX:
I m Using Process P= runtime.getRunTime().exec(FilePath)
where FilePath Variable is having value: mysql -u root -proot test< c:\test.mysql
I am Using Windiws environment. while if I run the FilePath in CmdLine, it will give the perfect reesult.
Highly thankful or help.
I had the same problem!
Actually the only thing that I could make work (on Windows, havent tested other platforms) is using batch files:
here is the code:
public class MysqlDatabase {
private int BUFFER = 10485760;
private String host, port, user, password, db;
public MysqlDatabase(String host, String port, String user, String password, String db) {
this.host = host;
this.port = port;
this.user = user;
this.password = password;
this.db = db;
}
public boolean restoreDatabase(String filepath) throws Exception {
String comando = "mysql " + db + " --host=" + host + " --port=" + port
+ " --user=" + user + " --password=" + password
+ " < " + filepath;
File f = new File("restore.bat");
FileOutputStream fos = new FileOutputStream(f);
fos.write(comando.getBytes());
fos.close();
Process run = Runtime.getRuntime().exec("cmd /C start restore.bat ");
return true;
}
public String getFull() throws Exception {
Process run = Runtime.getRuntime().exec(
"mysqldump --host=" + host + " --port=" + port
+ " --user=" + user + " --password=" + password
+ " --opt "
+ "" + db);
InputStream in = run.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder temp = new StringBuilder();
int count;
char[] cbuf = new char[BUFFER];
while ((count = br.read(cbuf, 0, BUFFER)) != -1) {
temp.append(cbuf, 0, count);
}
br.close();
in.close();
return temp.toString();
}}
I think we need some more information. As long as the paths are set up the same, if it will run from the command line, it should run the same from Runtime.exec(). What errors do you see?
Try setting the commend up in a script so you can echo the paths and the command output to a file to look at later. In UNIX that would look like
LOGFILE=my.log
echo $PATH > $LOGFILE
env >> $LOGFILE
mysql -u root -proot test< c:\test.mysql >> $LOGFILE 2>&1
It looks like you're using Windows, so I don't know how to set of the command file exactly this way; what's important is to make sure you're sending the error output of the mysql commend to the file.