DBInterface.connect returns MySQL.Connection(disconnected) - mysql

I'm trying to connect to a MySQL database. In the Documentation its recommended to use DBInterface.connect with a Type MySQL.Connection Object. The Database im trying to connect to gets listed with the mysql> SHOW DATABASES; command so there should be no problem on the MySQL side of things.
For now I implemented:
module Database
using MySQL
using DBInterface
const HOST = "localhost"
const USER = "root"
const PASS = "#####"
const DB = "databank"
const CONN = DBInterface.connect(MySQL.Connection, HOST, USER, PASS, db=DB)
export CONN
disconnect() = DBInterface.close!(CONN)
# gets called for cleanup
atexit(disconnect)
end
But when I call CONN from the REPL I get:
julia> using Database
julia> CONN
MySQL.Connection(disconnected)
julia>
I already checked this Question for answeres, but my implementation should be the same.
Later down the line I was hoping to use DBInterface.execute(CONN, sql) but I get the error ERROR: mysql connection has been closed or disconnected

Related

Not able to connect to MySQL database when reading db parameters from config file

Okay.. I'm having a really strange issue and not able to figure out why it's happening. I have an AWS lambda function (Node.js) which connects to a MySQL database.
When DB parameters are hardcoded in Node.js, it works fine. Please see below.
const con = mysql.createConnection({
host : "myapp.something.us-west-2.rds.amazonaws.com",
user : "someuser",
password : "somepassword",
port : "3306",
database : "somedatabse"
});
const query = util.promisify(con.query).bind(con);
When I try to connect to the DB by reading these parameters from a config file or lambda environment variables, I get this error.
"ERROR Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)"
const con = mysql.createConnection({
host : dbHost,
user : dbUser,
password : dbPassword,
port : dbPort,
database : dbName
});
const query = util.promisify(con.query).bind(con);
// Retrieving DB parameters from my config file like this. Values are being retrieved successfully.
dbHost = dbConfig.dev_db_host;
dbUser = dbConfig.dev_db_user;
dbPassword = dbConfig.dev_db_password;
dbPort = dbConfig.dev_db_port;
dbName = dbConfig.dev_db_name;
// Able to log all these values correctly.
console.log(dbHost); // myapp.something.us-west-2.rds.amazonaws.com
console.log(dbUser);// someuser
console.log(dbPassword); // somepassword
console.log(dbPort); // 3306
console.log(dbName); // somedatabase
Note - I am able to retrieve the values successfully from config file. I verified by logging the info. Not sure why the DB connection is failing.
Also, I run into the exact same issue when I read the DB parameters from lambda environment variables.
Any help is appreciated. Thanks in advance!

Failing to connect to MySQL in Dlang with vibe-d and mysql-native

I have simple vibe-D program which is trying to connect to SQL:
import std.stdio;
import mysql;
import vibe.d;
void main()
{
MySQLPool db_pool = new MySQLPool("localhost","root","","dbname",3306);
Connection db = db_pool.lockConnection();
// same thing happens with:
// string connectionStr = "host=localhost;port=3306;user=root;db=dbname";
// db = new Connection(connectionStr);
}
(I deleted everything else for simplification)
Dependencies:
"dependencies": {
"mysql-native": "~>3.2.0",
"vibe-d": "~>0.9.4"
}
And it fails to connect with:
object.Exception#../../../.dub/packages/vibe-core-1.22.4/vibe-core/source/vibe/core/net.d(256): Failed to connect to [0:0:0:0:0:0:0:1]:3306: refused
When I try it without vibe-d in the dub project (using phobos sockets) it connects with no problem. What am I doing wrong?
that's an ipv6 address.... is your mysql listening on that interface? might help trying 127.0.0.1 instead of localhost and seeing what happens.
can also consider reconfiguring mysql to listen on all interfaces too, including the ipv6

How to connect to AWS MySQL database from Java?

I want to connect to AWS MySQL database instance. Here is my code:
val hikari = HikariConfig().run {
driverClassName = "com.mysql.jdbc.Driver"
jdbcUrl = "jdbc:mysql://${mainConfig.databaseHost}:${mainConfig.databasePort}" +
"?user=username&password=password"
username = Config.DATABASE_USER
password = Config.DATABASE_PASSWORD
isAutoCommit = false
transactionIsolation = "TRANSACTION_REPEATABLE_READ"
return HikariDataSource(this)
}
Database.connect(hikari(config))
And my mainConfig.databaseHost looks like: mydatabase.xyz.region.rds.amazonaws.com.
So, this connection is working but I can't to exec any SQL statements because:
java.sql.SQLException: No database selected
I've tried to specify database name in my jdbc url but it causes exception.
So how can I connect to specified AWS database?
After research I found that DB identifier and DB name are different, so I specified DB name in jdbc url and now it working!

MySQL connection pooling in Python2.7 doesn't work as expected. Facing issue with close() function of connection pool

I have taken the python sample code for MySQL Connection pool and tried to execute it with django framework. I'm able to execute the queries and retrieve the data if I don't close the cursor and connection object. When I call close() function connection object it's failing with following error, Please help me to solve this.
ProgrammingError at /settings
1045 (28000): Access denied for user 'root'#'localhost' (using password: NO)
Method: GET
Request URL: http://sample.app.com/settings
Django Version: 1.11.5
Exception Type: ProgrammingError
Exception Value: 1045 (28000): Access denied for user 'root'#'localhost' (using password: NO)
Exception Location: venv/local/lib/python2.7/site-packages/mysql/connector/connection.py in _auth_switch_request, line 256 Python Executable: venv/bin/python2
Python Version: 2.7.17
The code which I'm using, Coding in bold are creating the issue. If don't close connection, its working fine. when i close it doesn't work and throws an error.
db_pool.py
import mysql.connector.pooling
dbconfig = {
"host":"127.0.0.1",
"port":"3306",
"user":"root",
"password":"root",
"database":"test",
}
class MySQLPool(object):
"""
create a pool when connect mysql.
"""
def __init__(self, host="127.0.0.1", port="3306", user="root",
password="root", database="test", pool_name="mypool",
pool_size=3):
res = {}
self._host = host
self._port = port
self._user = user
self._password = password
self._database = database
res["host"] = self._host
res["port"] = self._port
res["user"] = self._user
res["password"] = self._password
res["database"] = self._database
self.dbconfig = res
self.pool = self.create_pool(pool_name=pool_name, pool_size=pool_size)
def create_pool(self, pool_name="mypool", pool_size=3):
"""
Create a connection pool
"""
pool = mysql.connector.pooling.MySQLConnectionPool(
pool_name=pool_name,
pool_size=pool_size,
pool_reset_session=True,
**self.dbconfig)
return pool
> > def close(self, conn, cursor):
> > """ Here I'm facing issue, close is causing the issue. this close must release the connection object and add it to the connection pool. """
> > cursor.close()
> > conn.close()
def execute(self, sql, args=None, commit=False):
"""
Execute a sql
"""
# get connection form connection pool.
conn = self.pool.get_connection()
cursor = conn.cursor()
if args:
cursor.execute(sql, args)
else:
cursor.execute(sql)
if commit is True:
conn.commit()
self.close(conn, cursor)
return None
else:
res = cursor.fetchall()
self.close(conn, cursor)
return res
Using above code in another file db_operation.py
from db_pool import MySQLPool
def testing(request, bid, *args, **kwargs):
mysql_pool = MySQLPool()
query = "select * from test.table1;"
result = mysql_pool.execute(query)
print 'RESULT : ', result
Please help me to solve this or share if any best examples to use connection pool properly.
Thanks in advance.
I have solved this issue. By default pool_reset_session is set to True and modified this to False. Now, it's working fine.
When pool_reset_session is true, it's resetting the session with default config's for host, user and no password. As per my current DB connection, it will not allow without password. So, pool_reset_session is caused an issue and solved it.
Thanks.

SphinxQL + sphinxsearch table doesn't exists

Today I was trying to use sphinxsearch with SphinxQL but something going bad =\
First I installed sphinxsearch then I configured it, after that I created index forum_index using indexer --all. All finished without errors.
Then I included SphinxQl to my project, typed host and port which is listening sphinx and tried to make a query like in ReadMe of SphinxQL:
// create a SphinxQL Connection object to use with SphinxQL
$conn = new Connection();
$conn->setParams(array('host' => 'localhost', 'port' => 9306))
;
But it caused a database access error:
access denied www-data#localhost password NO
After that I set parameters of username and password in SphinxQL using
mysqli::real_connect()
Previous errors disappeared
Then I tried to make a test query:
$query = SphinxQL::create($conn)->select('column_one', 'colume_two')
->from('forum_index');
$result = $query->execute();
But I get an error:
table forum_index doesn't exists
I have a feel that my SphinxQL doesn't see sphinx or sphinx config and tries to make a simple query.
Have you any idea what's going wrong?
Please go to command line use the following command
mysql -P9306 --protocol=tcp --prompt='sphinxQL> '
Once get sphinxQL prompt enter the following command
sphinxQL> show tables;
If you set up everything correctly you can see the forum_index table in the list. Else check your searchd configuration section in your sphinx.conf file for proper configuration. My configuration look like this
searchd {
listen = 9315
listen = 9306:mysql41
log = /Users/XXXX/projects/sphinx/data/searchd.log
query_log = /Users/XXXX/projects/sphinx/data/query.log
read_timeout = 5
max_children = 30
pid_file = /Users/XXXX/projects/sphinx/data/searchd.pid
max_matches = 1000
seamless_rotate = 1
preopen_indexes = 0
unlink_old = 1
workers = threads
thread_stack = 1024K
}
I solved my problem by setting host = '127.0.0.1' in SphinxQL params