Context:
I am trying to use mySQL in my Xcode c++ project. And I have this simple program available to connect to mysql:
int main(){
if(!mysql_real_connect(&mysql, "localhost", "root", "PassWord", "DB", 0, NULL, 0)) {
printf("connecting to Mysql error:%d from %s\n",mysql_errno(&mysql), mysql_error(&mysql));
return -1;
}else {
printf("Connected Mysql successful!\n");
}
mysql_close(&mysql);
return 0;
}
However, I was able to connect to MySQL. After I ran this CML in my terminal
export DYLD_LIBRARY_PATH=/usr/local/lib
the program doesn't work anymore with the error showing:
(my code in Xcode is below:)
I got this Error in Xcode command:
I am still able to log in to mySQL in CML with
mysql -u root -p
And By Showing all port variables, the port shows shows it is running on 3306
SHOW GLOBAL VARIABLES LIKE 'PORT';
So everything is still normal in Terminal.
Also I tried to unset the DYLD_LIBRARY_PATH but got no luck.
I am wondering what is the reason to cause the problem and any possible resolutions/workaround.
Related
Basically, I am trying to connect to a MySQL Database using Connector C drivers for MySQL. I am writing the code in Netbeans on a Linux system. But here is the mystery: I can connect to my database in Debug Mode, but not Release Mode??? I am using Netbeans as my IDE on Linux, and I set up all the libraries and include folders using the dropdown under project properties so it applies the properties to both the Debug Configuration and Release Configuration, and yet it will connect to the database when I execute in Debug, but not when I execute in Run - ??? I simplified the code to show you the actual connection code:
int readDB(void) {
MYSQL *mysql = NULL;
char *server = "localhost";
char *user = "root";
char *password = "";
char *database = "myDB";
int port = 3306;
mysql = mysql_init(mysql);
if (!mysql) {
puts("Init failed, out of memory?");
return EXIT_FAILURE;
} else {
puts("SUCCESS!\n");
}
if (!mysql_real_connect(mysql,server,user,password,database,port,NULL,0)) {
puts("Connect failed\n");
}
return 1;
}
So when I run it in Debug, it prints "SUCCESS" and nothing else. When I run it, it prints "SUCCESS" followed by "Connect failed". I am at a loss. Could this be a problem with the IDE? Is there another IDE for C that works well on Linux that I should consider? Or am I missing something quite obvious?
Update:
calling mysql_error() revealed
"Can't connect to local MySQL server through socket '/tmp/mysql.sock'
(2)"
When using a mysql client library in most languages including C, if the hostname is specified as localhost the client library will attempt to connect through a unix domain socket. You can force connection using TCP/IP by specifying the hostname as 127.0.0.1
Yes they are one and the same but
If unix_socket is not NULL, the string specifies the socket or named
pipe to use. Note that the host parameter determines the type of the
connection.
Alternatively you can examine your mysql configuration to find out where the socket has been created when the server starts and use that as the unix_socket parameter.
Third alternative is to change your server configuration to create the socket on /tmp/
I'm a little green at this, and I hope the issue I'm having is a simple one...edit: new information at bottom
I need to make a connection to a remote mysql (Amazon RDS) database.
After following a few tutorials, I have unixodbc and libmyodbc installed and configured on the client, but when I try to connect via isql, I get the error
[08S01][unixODBC][MySQL][ODBC 5.1 Driver]Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
[ISQL]ERROR: Could not SQLConnect
The most confusing part about this error is that I'm not trying to connect to a local database, but rather to a remote one. I do not have a mysql.sock file on the client...this isn't the issue though is it?
I'm sensing a configuration error but I'm just not sure what it could be.
If I run odbcinst -j then the output is:
DRIVERS............: /etc/unixODBC/odbcinst.ini
SYSTEM DATA SOURCES: /etc/unixODBC/odbc.ini
USER DATA SOURCES..: /root/.odbc.ini
The content of /etc/unixODBC/odbcinst.ini is:
[MySQL]
Description = ODBC for MySQL
Driver = /usr/lib64/libmyodbc5.so
Setup = /usr/lib64/unixODBC/libodbcmyS.so
UsageCount = 5
[MySQL ODBC 515 Driver]
Description = ODBC 5.515 for MySQL
DRIVER = /usr/lib64/libmyodbc5-5.1.5.so
SETUP = /usr/lib64/unixODBC/libodbcmyS.so
UsageCount = 3
Please note that I had to make up this configuration myself, I did a find for libmyodbc* and found these two .so files, thus set up a driver for each of them. A search for libodbcmyS* yields:
/usr/lib64/unixODBC/libodbcmyS.so.1
/usr/lib64/unixODBC/libodbcmyS.so
/usr/lib64/unixODBC/libodbcmyS.so.1.0.0
So, I don't know what else that configuration could be.
The content of /etc/unixODBC/odbc.ini is:
[target_db]
Driver = MySQL
Server = [servername.com]
Port = 3306
Database = [databasename]
Option = 2
User = [username]
Password = [password]
I've tried different options in "Driver", changing it from MySQL, to MySQL ODBC 515 Driver, to the path to the .so file (eg: /usr/lib64/libmyodbc5.so) and all yield the same result.
I'm running:
odbcinst -i -d -f /etc/unixODBC/odbcinst.ini
Followed by:
odbcinst -i -s -l -f /etc/unixODBC/odbc.ini
Followed by:
odbcinst -s -q
Which prints out the name of my connection, ie [target_db]
Then, I try the connect:
isql -v target_db user password
or just
isql -v target_db
and get the error shown above.
Anyone happen to know what I'm doing wrong here? Thanks a bunch-
EDIT:
Wanted to mention that I'm able to connect to the database from this server using the mysql command line tools.
I installed a local mysql database, and I'm able to connect to this using isql. It seems to be ignoring my odbc.ini file entirely, i have to enter a name with the command, ie isql -v test-database, but it still tries to connect to localhost despite my settings.
I feel as though I've tried everything but will keep at it and will post if i find a solution.
You could try to connect using the ip of your server instead of the dns entry on the "Server" line of odbc.ini.. Have you verified the driver is installed with phpinfo()?
Try to set the environment variable ODBCINI with the path of your odbc.ini file.
Keep in mind that the odbc.ini file you point to must be "write-accessible" by the user that is running the program (i.e. the user must have permissions to write in this file).
chmod g+w .odbc.ini did it for me since we run the DB with ORACLE-Start and the crs-User seems to be in charge
How would I connect to my VPS based MySQL database remotely (from a cloud based app) using the Ruby Net::SSH or Net::SSH::Gateway gems and key, not password, authentication?
And then connect to the database with Sequel or DataMapper. I'm assuming that after I manage to get the SSH connection working, I would just setup a Sequel/DM connection to 'sql_user#localhost:3306/database'.
I did locate a couple of similar question here, but they all use password authentication, not keys, and only demonstrate executing raw commands to query the database.
UPDATE: I just cannot seem to get this (Net::SSH with key manager) to work.
UPDATE2: Alright I have managed to get authorization when logging in from a computer that has authorized keys stored in the users local .ssh folder, with the following (port is my custom SQL port on the VPS):
sql_gate = Net::SSH::Gateway.new('192.xxx.xxx.xx','sqluser', port: 26000)
However, I will not be able to create a .ssh folder in the app's VM, so I need to somehow pass the path and filename (I will be creating a public key just for SQL access for specified user) as an option ... but haven't been able to figure out how.
UPDATE: Just need to figure out DataMapper access now. Current code being tested (remote_user_sql is my Ubuntu user, sql_user is the MySQL database user with localhost/127.0.0.1 privileges):
require 'net/ssh/gateway'
require 'data_mapper'
require 'dm-mysql-adapter'
class User
include DataMapp......
.
.
end
ssh_gate = Net::SSH::Gateway.new('192.n.n.n','remote_user_sql', {port: 25000, keys: ["sql_rsa"], keys_only: true})
port = ssh_gate.open('localhost',3306,3307)
child = fork do
DataMapper.setup(:default, {
adapter: 'mysql',
database: 'sql_test',
username: 'sql_user',
password: 'passwd',
host: 'localhost',
port: port})
DataMapper.auto_upgrade!
exit
end
puts "child: #{child}"
Process.wait
ssh_gate.close(port)
My solution, in two parts:
Well I have figured how to make the Net::SSH::Gateway gem using a specified keyfile, and then connect to the VPS through ssh via a port other than 22:
Part 1: Net::SSH::Gateway key authentication
First you must generate the keyfiles you want to use, copy the .pub to the remove server and append it to the ~/.ssh/authorized_keys file (cat sql_rsa.pub >> authorized_keys), and then make sure user_sql (the user I created on the VPS to be used only for this purpose) has been added to AllowUsers list in sshd_config. Make note of port used for ssh (25000 for this example) and use the following code to establish the connection:
ssh_gate = Net::SSH::Gateway.new('192.n.n.n','user_sql', {port: 25000, keys: ["sql_rsa"], keys_only: true})
That will read the keyfile sql_rsa in the same directory as script file, then create a new ssh gateway for 'user_sql'#'192.n.n.n' on port 25000.
I can successfully execute raw shell commands on the remove VPS with:
ssh_gate.exec("ls -la")
To close:
ssh_gate.shutdown!
Unfortunately I am still having problems using DataMapper (do-mysql-adapter) to use the gateway. I will update this answer if I figure that part out, but at least the first half of the problem has been solved.
These are the errors that DataMapper::Logger has reported:
When 127.0.0.1 was used:
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) (code: 2002, sql state: HY000, query: , uri: )
When localhost was used:
Access denied for user 'user_sql'#'localhost' (using password: YES) (code: 1045, sql state: 28000, query: , uri: )
When the VPS hostname was used:
Unknown MySQL server host 'hostname' (25) (code: 2005, sql state: HY000, query: , uri: )
UPDATE (No success yet): So far the only way I can access the remote MySQL database is by using Net::SSH::Gateway to establish a gateway, and then use the .sshmethod to open a new Net::SSH connection over that gateway, like so:
ssh_gate.ssh('192.n.n.n','user_sql',{port: 25000, keys: ["sql_rsa"], keys_only: true}) do |ssh|
ssh.exec("mysql -u sql_user -p'passwd' -h localhost -P 3306 -e 'SELECT DATABASE();'")
end
In other words, I can only execute SQL commands using the mysql command line. I cannot figure out how to get Sequel or DataMapper to use the gateway to connect.
Part 2: DataMapper/Sequel/mysql2 connection through Net::SSH::Gateway
Make sure your MySQL server is bound to 127.0.0.1 in /etc/mysql/my.cnf, setup your connection - DataMapper example:
DataMapper.setup(:default, {
adapter: 'mysql',
database: 'DATABASE',
username: 'username',
password: 'passwd',
host: '127.0.0.1',
port: 3307}) # local port being forwarded via Net::SSH:Gateway
Followed by any class table definitions and DataMapper.finalize if required. Note that DataMapper doesn't actually connect to the remote MySQL server until either an auto_upgrade!, auto_migrate!, or query is executed, so no need to create the forwarded port yet.
Then create a new Net::SSH::Gateway, and then whenever you need DataMapper/Sequel to access the remote database, just open a port for the process, like so:
port = ssh_gate.open('127.0.0.1',3306,3307)
child = fork do
DataMapper.auto_upgrade! # DM call that accesses MySQL server
exit
end
Process.wait
ssh_gate.close(port)
You may want to put the Net::SSH::Gateway/.open code in a begin..ensure..end block, ensure'ing the port closure and gateway shutdown.
I had to use a fork and Process.wait to establish the connection, without it the method just hangs.
I've set up a wordpress install on appfog (using rackspace), and cloned the install to my local machine for development. I know the install works (using MAMP) because I created a local mysql database and changed wp-config.php to point to it. However, I want to develop without having to change wp-config.php every time I commit. After doing some research, it seems like the Appfog service Caldecott lets me tunnel into the mysql database on the server, using af tunnel. Unfortunately, I'm having issues with getting it working. Even if I change my MAMP mysql port to something like 8889, and tunnel mysql through port 3306, it looks like it's connected but I still get "Error establishing a database connection" when loading my localhost Wordpress. When I quit the mysql monitor (using ctrl+x, ctrl+c), I get a message stating "Error: 'mysql' execution failed; is it in your $PATH?'. Originally, no, it wasn't, but I've fixed my PATH variable on my local machine so that when I go to Terminal and just type mysql, it loads up.
So I guess my question is 2 parts:
1.)Am I going with the right approach for Wordpress development on my local machine
and
2.)If so, why is the tunnel not working?
One way to deal with this is to mimic the VCAP_SERVICES environment variable on your local system with your local database settings. This would allow you to use the same custom AppFog wp-config.php file which looks at VCAP_SERVICES to get its db creds.
export VCAP_SERVICES='{"mysql-5.1": [{"credentials": {
"hostname": "localhost",
"port": 3306,
"password": "root",
"name": "LOCAL_DATABASE_NAME",
"user": "root"}}]}'
EDIT: You will need to restart the Apache server in MAMP after setting this env var. (Thanks Dex)
This will eliminate the need to point your development code at your production database.
simply test for whether vcap_services are available. if they are, use one config. if they arent, use a different config.
here is an example of my local + appfog development website configuration file.
if(getenv("VCAP_SERVICES")){
//if in webserver
$services_json = json_decode(getenv("VCAP_SERVICES"),true);
$mysql_config = $services_json["mysql-5.1"][0]["credentials"];
$username = $mysql_config["username"];
$password = $mysql_config["password"];
$hostname = $mysql_config["hostname"];
$port = $mysql_config["port"];
$db = $mysql_config["name"];
define("DB_SERVER", "$hostname");
define("DB_USER", "$username");//enter your database username
define("DB_PASS", "$password");//databse password
define("DB_NAME", "$db");//database name
} else {
//if in local development
define("DB_SERVER", "localhost");
define("DB_USER", "website");//enter your database username
define("DB_PASS", "dfgdfgdf");//databse password
define("DB_NAME", "fgdf_web");//database name
}
also, you can use .afignore same way you'd use .gitignore to ignore some files from the af update feature. u can update once with appropriate config, then add afignore, then it will never get updated again.
Here is a quick and very dirty script to automate the process based on Tim Santeford's answer. Be sure to change the LOCAL_DATABASE_NAME
#!/bin/bash
export VCAP_SERVICES='{"mysql-5.1": [{"credentials": {"hostname": "localhost", "port": 8889, "password": "root", "name": "LOCAL_DATABASE_NAME", "user": "root"}}]}'
/Applications/MAMP/Library/bin/httpd -k stop
sleep 3
/Applications/MAMP/Library/bin/httpd -k start
I have two computers, one install windows 7 , another is CentOS 5.8
In CentOS...
I use yum command to install httpd(apache2.2), php5.3.3 and mysql.
yum install httpd
yum install php53
yum install pdo
yum install php53-mysql
First I check the phpinfo, the pdo, pdo_mysql is success extends,
then I also check php -m in CentOS Terminal , have extend pdo and pdo_mysql, too.
I run same code between windows 7 and CentOS
window success, but centos fail
Two files, db.php and dbtest.php
Here is db.php:
<?php
class DB
{
private $conn;
#### construct ####
public function __construct( $dsn , $db_user , $db_password , $showError = false )
{
try
{
$this->conn = new PDO( $dsn , $db_user , $db_password );
if( $showError ) // set error information show or not.
{
$this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
else
{
$this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
}
$setUtf8 = $this->conn->prepare( 'set names utf8' ); // set encoded by utf8
$setUtf8->execute();
}
catch( PDOException $err )
{
return false;
}
}
}
?>
and here is dbtest.php:
<?php
require_once( "db.php" );
$link_test = new DB( "mysql:dbname=pdotest;port=3306;host=192.168.1.127", "root" , "123456" );
var_dump($link_test);
?>
When dump in windows , the result is:
object(DB)#1 (1) { ["conn":"DB":private]=> object(PDO)#2 (0), { } }
dump in CentOS, the result is:
object(DB)#1 (1) { ["conn":"DB":private]=> NULL }
Can anyone tell me why connect fail in CentOS??
Edit at 2012/10/24 16:10 (Asia/Taipei)
For test many hour, I guess is php pdo have problem...
because in my LAN, I can connect any 3306 port mysql by CentOS Terminal
but in php pdo_mysql class, I can't link any mysql(even CentOS local's mysql )
so...how to check my pdo_mysql extension is operate normally?
PS: Sorry,I have poor English :(
PHP/PDO on Linux will attempt to connect via a socket for local connections. You configure the location of this socket in the pdo_mysql.default_socket property in php.ini.
You will of course run into Bug #60155 which is fixed in 5.3.9 (I think) so I would definitely advise upgrading beyond version 5.3.3.
First, thank you to answer my question : )
Focus on socket, I already tried two ways:
1) Just like you say, I modify php.ini , add pdo_mysql.default_socket
then restart httpd service, but pdo mysql connection still fail
2) I modify dbtest.php line 3 (#3) , part of DSN
Original=> "mysql:dbname=pdotest;port=3306;host=192.168.1.127"
New => "mysql:unix_socket=/var/lib/mysql/mysql.sock;dbname=pdotest;port=3306;host=192.168.1.127"
, but connection still fail
I also try original mysql_connect to test link db, It's work!
According to your suggest, I will change php to another version(Maybe 5.4.8 or lower then 5.3.3) later, then post the result
Thanks!
Waste a lot of time...finally I get the solution!!
When I saw this question << Click link to see question
This answer solve my problem.
Selinux default setting is close httpd_can_network_connect and httpd_can_network_connect_db
Just open it! PDO connection will operate normally :)
Command:
setsebool -P httpd_can_network_connect=1
setsebool -P httpd_can_network_connect_db=1
Thank you, Michael Berkowski