DB2 SQL connection in Protractor - How To - sql

I am new to Protractor and still learning. In my conf.js file I have (maybe incorrectly?) set up a connection to a database:
mysql = require('C:/.../AppData/Roaming/npm/node_modules/mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'username',
password : 'password',
database : '//xxxxxxx.xxx.xx:nnnnn/xxxxxxxx'
});
connection.connect();
Then in my test I attempt to query for data to use:
//SQL to get Random Invoice Ref
var invRef = SELECT foo FROM table.table
WHERE condition = myData
ORDER BY RAND()
FETCH FIRST ROW ONLY;
But, it's giving me this error:
invRef = SELECT foo FROM table.table ('foo' is underlined with the '^' character)
Exception loading: C:\...\testSpec.js
Error -- fail
I suspect I have things set up incorrectly, to say the least. Can someone tell me the proper way to define a db2 SQL connection in Protractor? Am I also using it correctly in my test?

Just missing some double quotes there:
//SQL to get Random Invoice Ref
var invRef = "SELECT foo FROM table.table " +
"WHERE condition = myData " +
"ORDER BY RAND() " +
"FETCH FIRST ROW ONLY;";
Given you're setting up SQL access from Protractor NodeJS side of things to load test data from there to fill up forms for example.
Side note: Doc on Protractor components will help you separate concerns.
UPDATE
DB2 SQL in NodeJS
Install IBM client from here. Match your server version.
Use a NodeJS DB2 library like this one.

Related

Getting Timeout while inserting in transaction using node-mssql package sqlserver

I recently started using mssql package in my Node-Express Application for accessing the DB.
I read through various documents, including the implementation and tutorial on how to establish and use a connection. Here are the few things that I am confused upon.
Clarification
Is it a good practice to keep a connection open across the application, i.e. I have my current implementation like this.
global.sql = await mssql.connect(config, function (err) { /*LOGS*/});
And wherever, I query, I query like
function getItems(){
await sql.query`select * from tbl where val in (${values})
}
Is it the right way of doing things, or should I do it like this?
function getItems(){
const sql = mssql.connect()
await sql.query`select * from tbl where val in (${values})
}
Query:
I was going through the doc in the NPM readme.
There queries are done in 2 ways:
await sql.query`select * from mytable where id = ${value}`
2. ```
await new sql.Request().query('select 1 as number')
What is the difference between both, and which one has to be used when?
Blocker:
I am able to run a insert query by
await sql.query`insert into tbl (val1, val2) values (${item}, ${userId})`
// sql is the connection for the global variable as mentioned above
I tried creating the above mentioned query in Transaction. For that I have used this
transaction = new sql.Transaction()
await transaction.begin();
let request = new sql.Request(transaction);
await request.query(/* insert into tbl .... */)
It was working fine, but after some time, when I retried, the query started giving timeout with error Timeout: Request failed to complete in 15000ms
Can't understand why this is happening?
I tried running the same query from the sql server management studio, and it was working as expected

What is causing the error 'User lacks privilege or object not found: FieldName'

Using a MS Access Database to hold my information, it has been working fine up and till this point i created a new method named CreateLicense() which takes in the license class i made and writes it to the database.
When the code is run it will spit out a error stating 'user lacks privilege or object not found: EXPIRED'
Already tried changing the fields names of Expired incase it was a reserved word or something. Also tried removing the Expired field but then flags the same error but with CONTACT instead.
INSERT INTO Licenses (Name, DateRedeemed, Expired, LicenseLength, Contact) VALUES ('name','25/Jun/2019','02/Jul/2019','2','contact')
user lacks privilege or object not found: EXPIRED
Here is the output of my SQL statement
This is the code
public boolean CreateLicense(License newLicense) {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
File currentDir = new File(""); // Creates a new file
String newFilePath = "jdbc:ucanaccess://" + currentDir.getAbsolutePath().toString() + "\\store\\data\\database1.accdb";
Connection conn = DriverManager.getConnection(newFilePath);
Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO Licenses (Name, DateRedeemed, Expired, LicenseLength, Contact) VALUES "
//Values for the SQL Statement
+ "('" + newLicense.getName()//Start Line
+ "','" + newLicense.getRedeemed()//Middle Lines
+ "','" + newLicense.getExpired()//Middle Lines
+ "','" + newLicense.getLicenseLength()//Middle Lines
+ "','" + newLicense.getContact()+ "')");//End Line
conn.close();
return true;
} catch (Exception ex) {
String message = ex.getMessage();
System.out.println(message);
return false;
}
}
Some additional information to help solve
The table name is Licenses
Field Names and their type
ID - Autonumber
Name - String
DateRedeemed - String
Expired - String
LicenseLength- int
Contact- String
UPDATE
I created a query using the query design in access, this supplied the information to the database fine, so it cant be the sql which is the issue.
UPDATE
When i rename the table in the database and run the application i get the same error but with the table name instead, i am going to create a new database and see if that solves anything
Solution Found
LicenseLength is an Int but you are surrounding it with quotes like it is a string. Also, have you tried using a parameterized query like
String sql = "INSERT INTO Licenses (Name, DateRedeemed, Expired, LicenseLength, Contact) VALUES (?, ? ,?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, newLicense.getName());
stmt.setString(2, newLicense.getRedeemed());
stmt.setString(3, newLicense.getExpired());
stmt.setInt(4, newLicense.getLicenseLength());
stmt.setString(5, newLicense.getContact());
It was a pure moment of stupidity, i had a created a backup database which was saved just outside the fat jar directory, as when you create a fat jar it wipes the folder. At the some point i have opened that to test something forgotten to close and that is where i added the license table.
So when i run the application it actually couldn't find the table due to the file path, I figured this out by testing my other methods, i used my createUser() method which showed which database it was being written to.
For Other users
If you get this error, try the following
Apply Joakim's solution if you are using one large SQL string like i was as it could be a issue with your SQL statement.(And its better programming practise)
Look at your Table name and fields and make sure they are the exact same as your SQL
Run your application and test another method where it was previously working, if successful check where the application has written the value
If all else fails, delete the method, type it from scratch with no copy and paste, create a new database as i had this issue before when i used relationships between tables within my access database
I hope this solution helps others solve this issue.

Manually sanitize SQL parameters

I would like to run a script like:
CREATE LOGIN [me] WITH PASSWORD = #0
and run it like:
var createUserCommand = conn.CreateCommand();
createUserCommand.CommandText = script;
createUserCommand.Parameters.AddWithValue("#0", passwordDecrypted);
However, this throws:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near '#0'.
From what I read online (nowhere official, just from SO answers/comments) it is not possible to use SQL parameters with DDL statements. Link to official docs for this are welcome!
OK. I do need this parametrized. As I see it, there are 2 options:
I manually sanitize (.Replace("'", "''") => how can I do this best?
I call into .NET to sanitize for me. However I assume this is not sanitized within ADO.NET, but just past to SQL Server, and sanitized there...
What would be the best approach?
All you need to escape is the single ' to 2 x '
commandText = string.Format("CREATE LOGIN [me] WITH PASSWORD = '{0}'", pass.Replace("'", "''"));
An alternative would be to create a stored procedure with a password parameter and use it to build a CREATE LOGIN string which you then sp_executeSQL.

Not able to connect to OpenOffice Base - User lacks privilege or object not found Exception

I am trying to connect to an OpenOffice Base database from Java and execute a query, and have not been able to.
These are the steps I followed:
1) Created a Database 'TestDB.odb' in OpenOffice, and a table 'Movies' with columns (ID, Name, Director)
2) Downloaded hsqldb jar file and inclued in project build path
3) Used the following code to connect to it:
String file_name_prefix = "C:/Documents and Settings/327701/My Documents/TestDB.odb";
Connection con = null;
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:file:" + file_name_prefix, "sa","");
Statement statement = con.createStatement();
String query1 = "SELECT * FROM \"Movies\"";
ResultSet rs = statement.executeQuery(query1);
Althoug I'm able to connect to the Database, it throws the following exception on trying to execute the query:
org.hsqldb.HsqlException: user lacks privilege or object not found: Movies
Tried googling, but have not been able to resolve my problem. I'm stuck and it would be great if someone could guide me on how to fix this issue?
You cannot connect to an .odb database. The database you have connected to is in fact a separeate set of files with names such as TestDB.odb.script, etc.
Check http://user.services.openoffice.org/en/forum/viewtopic.php?f=83&t=17567 on how to use an HSQLDB database externally from OOo in server mode. You can connect to such databases with the HSQLDB jar.
OLD thread.
I lost 2 days of my life until I changed the property:
spring.jpa.properties.hibernate.globally_quoted_identifiers = false
I was using mysql before and then I changed to hsqldb in order to run some tests. I kinda copied and pasted this property without looking and then you know - Murphy's law ...
I hope it helps.

Groovy sql errors on remote Mysql server?

I'm using groovy gsql to query to Mysql database.
Everything goes well on localhost (testing mode), unfortunately when I switching to remote db groovy don't query db.
Here is the code :
def sqlModule = Sql.newInstance("jdbc:mysql://localhost/module-test", "b", "b", "com.mysql.jdbc.Driver")
def sampleQuery(int dataset) {
def SampleQueryList = []
// Sql query
sqlModule.eachRow("""
select b.*
from dataset_group_set_details a, array_data b
where dataset_id = "${dataset}"
and group_set_id = 1
and a.array_data_id = b.array_data_id ;""")
{
def addSample= new Sample(it.toRowResult())
addSample.id = "${it.array_data_id}" as int
addSample.dateCreatedSample = dateFormat.parse("${it.date_created}")
addSample.tissueTypeId = "${it.tissue_type_id}" as int
...
// Add Sample to SampleList
SampleQueryList << addSample
}
return SampleQueryList
In localhost mode, "return SampleQueryList" return a good list, but in remote mode (ex : jdbc:mysql://192.168.209.32/module-test) my list is empty.
Note : Db in localhost and remote are equals. Also, I have no error in remote mode.
Why, in localhost mode groovy quering my db and not in remote mode ?
Any ideas ?
With out more information it's impossible to say what's wrong for sure. Have you tried a simple
select * from tablename
query to make sure your getting a connection to the database? It's possible your trying to connect with the wrong user name and password. If you don't control the database restrictions may be in place limiting the length and complexity of queries you can execute on the remote server with the given user account.