java.sql.SQLException: Unable to load authentication plugin 'caching_sha2_password' - mysql

I'm trying to connect to MySQL database in Ktor application:
fun initDB() {
val url = "jdbc:mysql://user:pass#localhost:3306/databasename?useUnicode=true&serverTimezone=UTC"
val driver = "com.mysql.cj.jdbc.Driver"
Database.connect(url, driver)
}
...
fun getUsers(): String {
var json = ""
transaction {
val dbResult = Users.selectAll().orderBy(Users.lastName, true).limit(10)
...
json = Gson().toJson(users);
}
return json
}
But I receive the following error:
java.sql.SQLException: Unable to load authentication plugin
'caching_sha2_password'
Why does it happen? And how to fix it?
UPD
Eventually I've found a way to fix it: I've created new user in MySQL by command
CREATE USER 'nativeuser'#'localhost'
IDENTIFIED WITH mysql_native_password BY 'password';
then granted him all privileges and reconnected with new credentials. But the first question is still actual, because I don't have any settings like
default_authentication_plugin=caching_sha2_password
in my my.ini file.

Related

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

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.

How to config slick 3.2 connect to mysql by typesafe config package?

I have attempted official document for postgresql and change org.postgresql.ds.PGSimpleDataSource to slick.driver.MySQLDriver$
dataSourceClass = "slick.driver.MySQLDriver$"
properties = {
databaseName = "mydb"
user = "user"
password = "password"
}
numThreads = 10
scala code:
val config = DatabaseConfig.forConfig[JdbcProfile]("slick.mysql.local")
Output error:
Exception in thread "main" com.typesafe.config.ConfigException$Missing:
No configuration setting found for key 'slick.mysql.local.profile'
Seems it need a profile property but what value should be added?
============UPDATE========
config properties are under brackets:
slick.mysql.local {
dataSourceClass = "slick.driver.MySQLDriver$"
properties = {
databaseName = "mydb"
user = "user"
password = "password"
}
numThreads = 10
}
If you carefully read the docs, what they say is:
define a mydb key in some application.conf with your configuration
refer to that configuration using val db = Database.forConfig("mydb")
So I can only assume you're missing your slick.mysql.local key.
I also found it difficult to configure the database connector. Here is my config:
mysql {
dataSourceClass = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
properties = {
url = "jdbc:mysql://127.0.0.1:3306/dbName"
databaseName = "dbName" <= maybe not necessaray as also in the url
user = "root"
password = ""
}
numThreads = 10
}
Thanks to https://groups.google.com/forum/#!topic/scalaquery/WbR6yHzBj_8
I struggle some days and find a config can works.
driver = "slick.driver.MySQLDriver$"
db {
url = "jdbc:mysql://127.0.0.1:3306/develop_tdsystem?user=user&password=password"
driver = com.mysql.jdbc.Driver
maxThreads = 10
}
please notice there are some warning:
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
[warn] c.z.h.u.DriverDataSource - Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.

Connecting MySQL to Scala using slick

I am trying to connect MySQL database do scala application using slick 3.1
In demo which is provided by Typesafe, this code is used as application.conf :
h2mem1 = {
url = "jdbc:h2:mem:test1"
driver = org.h2.Driver
connectionPool = disabled
keepAliveConnection = true
}
I am running MySQL database on ampps apache server and now I am confused regarding what to enter as url and driver so that my application can connect to database?
Should my url be "localhost"?
Something like this:
database = {
url = "jdbc:mysql://localhost/test"
user = "user"
password = "pwd"
driver = com.mysql.jdbc.Driver
connectionPool = disabled
keepAliveConnection = true
}

Grails H2 Database DbConsole - Database backup

I have grails 2.0 which comes with H2 database and dbconsole.
I want to take the database backup from dbconsole:
databse url : "jdbc:mysql://localhost/opal"
Username : root
password: (none)
in the tools section of dbconsole there is a option to backup the database.
it will ask 3 things
Target file name: ~/backup.zip(by default)
Source directory:
Source database name: opal (name of my database)
when i press run , it gives error,
No database files have been found in directory E:/Workspace/opal for the database opal
can anybody suggest how to take the database backup.
I've never gotten that to work. If you just want a snapshot of data for development (load on startup) I found that using DBUnit to export/import the data worked great for me. I wrote a script to export it that I call from the console:
class DataExport {
def ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
def exportData() {
println "-->export"
def ds = ctx.dataSourceUnproxied
println ds.dump()
Connection jdbcConnection = ctx.dataSourceUnproxied.getConnection()
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
println connection.dump()
ITableFilter filter = new DatabaseSequenceFilter(connection);
IDataSet dataset = new FilteredDataSet(filter, connection.createDataSet());
FlatXmlDataSet.write(dataset, new File("full.xml").newWriter());
connection.close()
}
}
And then in bootstrap you can load it back in
Connection jdbcConnection
FlatXmlDataSet dataSet = new FlatXmlDataSetBuilder().build(new ClassPathResource('resources/data/full.xml').inputStream)
jdbcConnection = ctx.dataSource.getConnection()
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
try {
DatabaseOperation.INSERT.execute(connection, dataSet)
} catch(e) {
e.printStackTrace()
throw(e)
} finally {
jdbcConnection.close()
}
log.info 'data loaded'
I think this site would be quite helpful. Or, on taking dump of the database and to restore the database try snippet below:
mysqldump -u root -p my_database Table1 Table2 > /home/user/tablesDump.sql;
and to restore the table(s) back:
mysql -u root -p my_database_2
mysql> source /home/user/tablesDump.sql;
Both tables were created in my_database_2.