i just created my first AWS MySQL Database and want to connect to that from my scala application using Slick.
My config file shows:
awsMySQL = {
profile = "slick.jdbc.MySQLProfile$"
dataSourceClass = "slick.jdbc.DatabaseUrlDataSource"
properties = {
url = "jdbc:mysql://<databaseName>.cn17tbad2awy.eu-central-1.rds.amazonaws.com"
user = "foo"
password = "bar"
driver = com.mysql.cj.jdbc.Driver
}
connectionPool = disabled
keepAliveConnection = true
}
I just define a query to receive all my customers, but when exeuting this code i receive a SQLException: No database selected.
val db = Database.forConfig("awsMySQL")
val CustomersDAO = TableQuery[Customers]
val q1 = for (c <- CustomersDAO) yield c.name
val a = q1.result
val f = db.run(a)
Await.result(f, Duration.Inf)
I do not really understand this exception, because from my point of view by the url specifies the database. Could you please help me.
Thanks in advance.
I think you are pointing to the host where the MySQL service is running but not to the Database itself
Try to replace url = "jdbc:mysql://<databaseName>.cn17tbad2awy.eu-central-1.rds.amazonaws.com" with something like:
url = "jdbc:mysql://<databaseName>.cn17tbad2awy.eu-central-1.rds.amazonaws.com/DBSCHEMA"
Related
I'm trying to connect to a Google Cloud MySQL 5.7 instance using GAS and JDBC. I'm able to run the following without error:
var conn = Jdbc.getCloudSqlConnection("jdbc:google:mysql://my-instance-111111:us-central1:mydbname", user,userPwd)
But this doesn't connect to a specific database, i.e. when I run
var stmt = conn.createStatement();
var results = stmt.executeQuery('SELECT col FROM myTable;');
I get Error Exception: No database selected.
One approach to try to fix:
The GAS docs indicate that I can use advanced parameters to include the DB name, but when I run var conn = Jdbc.getCloudSqlConnection("jdbc:google:mysql://my-instance-111111:us-central1:mydbname", user,userPwd,mydbname) ,
I get Exception: The parameters (String,String,String,String) don't match the method signature for Jdbc.getCloudSqlConnection.
A collection of getCloudSqlConnection statements that I've tried based on a number of StackOverflow posts:
var conn = Jdbc.getCloudSqlConnection("jdbc:google:mysql://my-instance-111111:us-central1:mydbname/mydbname", user,userPwd)
var conn = Jdbc.getCloudSqlConnection("jdbc:google:mysql://my-instance-111111:us-central1:mydbname:3306/mydbname", user,userPwd)
var conn = Jdbc.getCloudSqlConnection("jdbc:google:mysql://my-instance-111111:us-central1:mydbname:3307/mydbname", user,userPwd)
For the above statements, I also tried replacing my-instance-111111:us-central1:mydbname with the public IP supplied on the GC overview webpage. All return Exception: Failed to establish a database connection. Check connection string, username and password.
I'm using user root and the appropriate password. I can enter the DB via the command line with the user and password that I'm supplying in GAS, so I don't think I'm supplying the wrong user and password.
Edit:
I went back to the docs like #AddonDepot mentioned and realized that I need to pass an object, but I still can't get this work....
var obj = {
connectTimeoutSeconds: 15,
database: "mydbname",
instance: "my-instance-111111:us-central1:mydbname",
password: userPwd,
queryTimeoutSeconds: 15,
user: user };
var conn = Jdbc.getCloudSqlConnection("jdbc:google:mysql://my-instance-111111:us-central1:mydbname", obj);
returns
Exception: The following connection properties are unsupported: database,instance,connectTimeoutSeconds,queryTimeoutSeconds. .
Did I do something wrong in creating the object? I'm guessing not, because GAS recognizes user and password. Why wouldn't it recognize the other advanced parameters?
We have to distinguish between database system instances (sometimes referred simply as database; I'll use instances) and databases within them. That means that you may have an instance but may not have created any database in it.
You can use Apps Script to create a new database in your instance:
const connectionName = 'connection-name:for-your:instance'
const dbName = 'database'
const username = 'user'
const password = 'password'
function createDB() {
const conn = Jdbc.getCloudSqlConnection(`jdbc:google:mysql://${connectionName}`, username, password)
conn.createStatement().execute('CREATE DATABASE ' + dbName)
}
Once you have the database created in your instance you can use it:
function useDB() {
const conn = Jdbc.getCloudSqlConnection(`jdbc:google:mysql://${connectionName}/${dbName}`, username, password)
// Use conn
}
References
JDBC (Google Apps Script guide)
I'm trying to introduce slick into my code to replace some existing jdbc code.
First of all I'd like to use a scala worksheet to run a really simple query, I want to pass in an integer id, and get back a string uuid. This is the simplest method in the whole codebase.
As I understand I need to make a connection to the database, setup an action, and then run the action. I have the following code:
val db = Database.forURL("jdbc:mysql://mysql-dev.${URL}/${DB}?autoReconnect=true&characterEncoding=UTF-8",
driver = "com.mysql.jdbc.Driver", user = "${user}",password= "${pass}")
val getUUID = sql"""SELECT ${UUIDFIELD} from users u WHERE u.${IDFIELD} = ${Id}""".as[String]
val uuid:String = db.run(getUUID)
println(uuid)
I'm pretty sure I don't have the driver setup correctly in the Database.forURL call, but also the worksheet is complaining that the result of db.run is not a string. How do I get to the string UUID value?
The db.run method returns a Future[_] type. You should use Await for getting result from it.
val db = Database.forURL("jdbc:mysql://mysql-dev.${URL}/${DB}?autoReconnect=true&characterEncoding=UTF-8",
driver = "com.mysql.jdbc.Driver", user = "${user}",password= "${pass}")
val getUUID = sql"""SELECT ${UUIDFIELD} from users u WHERE u.${IDFIELD} = ${Id}""".as[String]
val uuidFuture:Future[String] = db.run(getUUID)
import scala.concurrent._
import scala.concurrent.duration._
val uuid:String = Await.result(uuidFuture, Duration.Inf)
println(uuid)
Isn't my coding typing wrong way? I need create an update button so user can edit the information by using Matlab. After update, the button need connect to mySQL server 5.6 and ODBC connector.
This is my code:
% --- Executes on button press in update.
function update_Callback(hObject, eventdata, handles)
% hObject handle to update (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Display dialog box to confirm save
choice = questdlg('Confirm update to database?', ...
'', ...
'Yes','No','Yes');
% Handle dialog box response
switch choice
case 'Yes'
%Set preferences with setdbprefs.
setdbprefs('DataReturnFormat', 'cellarray');
%Make connection to database.
conn = database('animal_cbir', '', '');
%Test if database connection is valid
testConnection = isconnection(conn);
disp(testConnection);
fileID = getappdata(0,'namevalue');
imageID = fileID;
name = get(handles.edit11,'String');
commonName = get(handles.edit1,'String');
scientificName = get(handles.edit2,'String');
class = get(handles.edit3,'String');
diet = get(handles.edit4,'String');
habitat = get(handles.edit5,'String');
lifeSpan = get(handles.edit6,'String');
size = get(handles.edit7,'String');
weight = get(handles.edit8,'String');
characteristic = get(handles.edit10,'String');
tablename = 'animal';
colnames ={'imageID','name','commonName','scientificName','class','diet','habitat','lifeSpan','size','weight','characteristic'};
data = {imageID,name,commonName,scientificName,class,diet,habitat,lifeSpan,size,weight,characteristic};
disp (data);
whereClause = sprintf(['where imageID = "%s"'],fileID);
update(conn,tablename,colnames,data,whereClause);
updateSuccess = helpdlg('Existing animal species successfully updated in database.');
commit(conn);
case 'No'
end
Error I am getting:
No method 'setInt' with matching signature found for class 'sun.jdbc.odbc.JdbcOdbcPreparedStatement'.
Hope that anyone can help me solve it.
In my mvc web application, I am getting this error:
Anonymously Hosted DynamicMethods Assembly
Stack Trace : at Read_<>f__AnonymousType14(ObjectMaterializer1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext() at project.com.Concrete.DetailsRepository.GetDetails(String type) in path
Message : The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
When I run my site from local server it is working fine.
But when it runs at remote server it is giving above error
Here is my code:
var res=
(from r in DetailsTable
where r.Activated == true
group r by new { r.ActivationDate, r.ProductID, r.SubProductID } into t
select new { icount = t.Count(),
sActivationDate = t.Key.ActivationDate.ToShortDateString(),
iProductID = t.Key.ProductID,
iSubProductid = t.Key.SubProductID })
.OrderBy(r => r.icount);
Thanks
AS
The issue you're having is that your query is empty on the remote server where data exists on the local server.
I'm not exactly sure at which part in the query the exception is happening, so I'd suggest splitting your query in half.
var res=
from r in DetailsTable
where r.Activated == true;
if(res.Count() == 0)
return; // or handle gracefully as appropriate
var groups =
from r in res
group r by new { r.ActivationDate, r.ProductID, r.SubProductID } into t
select new { icount = t.Count(),
sActivationDate = t.Key.ActivationDate.ToShortDateString(),
iProductID = t.Key.ProductID,
iSubProductid = t.Key.SubProductID })
.OrderBy(r => r.icount);
I'm sure there is a more graceful way of doing this within a single query statement, but without more details I'm not sure exactly how to proceed.
I have the following django code working on an sqlite database but for some unknown reason I get a syntax error if I change the backend to MySQL...does django's ORM treat filtering differently in MySQL?
def wsjson(request,imei):
wstations = WS.objects.annotate(latest_wslog_date=Max('wslog__date'),latest_wslog_time=Max('wslog__time'))
logs = WSLog.objects.filter(date__in=[b.latest_wslog_date for b in wstations],time__in=[b.latest_wslog_time for b in wstations],imei__exact=imei)
data = serializers.serialize('json',logs)
return HttpResponse(data,'application/javascript')
The code basically gets the latest logs from WSlog corresponding to each record in WS and serializes it to json.
Models are defined as:
class WS(models.Model):
name = models.CharField(max_length=20)
imei = models.CharField(max_length=15)
description = models.TextField()
def __unicode__(self):
return self.name
class WSLog(models.Model):
imei = models.CharField(max_length=15)
date = models.DateField()
time = models.TimeField()
data1 = models.DecimalField(max_digits=8,decimal_places=3)
data2 = models.DecimalField(max_digits=8,decimal_places=3)
WS = models.ForeignKey(WS)
def __unicode__(self):
return self.imei
Ok finally managed to fix it with code below
def wsjson(request,imei):
wstations = WS.objects.annotate(latest_wslog_date=Max('wslog__date'),latest_wslog_time=Max('wslog__time'))logs = WSLog.objects.filter(date__in=[a.latest_wslog_date for a in wstations],time__in=[b.latest_wslog_time for b in wstations],imei__exact=imei)
data = serializers.serialize('json',logs)
return HttpResponse(data,'application/javascript')
the weird part was the original code worked as expected in an ubuntu machine running MySql but failed in a windows machine (also running MySql)