command line argument in js file for mongodb - javascript

I am running a js script to work on mongodb as
mongo localhost:27017/dbname mongodump_isp.js
In the mongodump_isp.js file, I am doing at the very beginning
conn= new Mongo();
db=conn.getDb("dbname");
I have to again provide the database name inside the js file. How can I provide that dynamically?

The conn part is not necessary but you can just set the "database" name like this:
var db = db.getSiblingDB("dbname");
And then all references to db afterwards will use that database, or you can set another variable to another db connection
But if what you are talking about is specifying the db value on the command line, then you do not need any extra lines in your code as the value of db is already set to what you specified.

Related

Inserting data from JS script into mysql database

I have created a script to count down whatever value I submit into a form and then output "the submitted value + the date of the moment I clicked on the submit button" as a result.
But now I want to store the result into my database every time I use the form by using SQL query and then echo all of these results in another page named "log.php" using SELECT SQL query.
var timelog = [];
function myF() {
countdown(s);
log = document.getElementById("log").innerHTML = s + 'at ' + new Date();
timelog.push(log);
}
function logged() {
document.getElementById("timeloggg").innerHTML = timelog;
}
I have tried to assign the result to a variable, but obviously, I cant use this variable outside of the script.
With some googling, I was told to use Ajax, but sadly I couldn't figure out how to insert the data using ajax, because all of the code examples out there are only about calling data from the database.
So any advice on how to insert the result into my database? I'm still a beginner so please explain in detail if you don't mind.
It is possible, of course, to insert data into your database from client side js, BUT DONT! I can't think of a way to do it that would not expose your database credentials, leaving you open to malicious actors.
What you need to do is set up a php script on your server, then send the data (either by POST or GET) you want inserted to that with an xhr request, and let that php script do the insert. HOWEVER, there is quite a bit to securing even that. Google "how to sanitize mysql inputs in php" and read several articles on it.
Depending on what you need to do, you can sanitize the inputs yourself, but the recommended way to do it is with prepared statements, which you will need to read the documentation for your specific implementation, whether it's mysqli or pdo in mySQL or some other library (say if you're using SQL, postGRE, Oracle, etc).
HTH
=================================================
Here is how to do it in js, BUT DONT DO THIS, unless you are never going to expose this code outside of your local computer.
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Provider=host;Data Source=table;User Id=user;Password=pass;";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
var sql = {{your sql statement}};
rs.Open(sql, connection);
connection.close;
==============================================
For php, do something like this, replacing host, user, pass, db with your actual credentials and hostname and database:
$db = new mysqli({host}, {user}, {pass}, {database});
if($db->connect_errno > 0){ die ("Unable to connect to database [{$db->connect_error}]"); }
to set the connection. If this is a publicly accessible php server, then there are rules about how to set up the connection so that you don't accidentally expose your credentials, but I'm going to skip that for now. You would basically save this into a file that's not accessible from the outside (above the document root, for instance) and then include it, but database security is a complex topic.
To get the values you passed in the query string of your ajax call:
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
Then to do the insert with a parameterized query:
$query = $db->prepare("
INSERT INTO your_table (field1, field2)
VALUES (?, ?)
");
$query->bind_param('ss', $val1, $val2);
$query->execute();
Now, here you're going to have to look at the documentation. 'ss' means that it's going to treat both of those values you're inserting as strings. I don't know the table set up, so you'll have to look up the right code for whatever you are actually inserting, like if they were integers, then 'ii', or 'si' would mean the first value was a string and the second one was an int.
Here are the allowed values:
i - integer
d - double
s - string
b - BLOB
but look at the documentation for prepared statements anyway. I used msqli in this example.
You might want to check Ajax requests.
I would suggest to start here.
What you will do is basically create asynchronous requests from javascript to a php file on your server.
Ajax allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it
is possible to update parts of a web page, without reloading the whole
page.

Passing only the required rows of data from CSV file to Jmeter based on a criteria

I have a csv file which has the input in the below format (It has no headers as first row):
India,QA,1200,
India,QA1,1201,
India,QA2,1202,
USA,Dev1,5580,
USA,Dev2,5580,
AUS,Dev3,3300,
AUS,Dev4,3301,
I have configured the CSV Data Set Config component and have given the respective path and variable name details. Snapshot below:
from the command line argument, i will be invoking the Jmeter jmeter.bat -t C:\Users\Dev\Desktop\JI\testscript.jmx -JCountry=Indiawhich also has a parameter called JCountry=India.
Now, I have to use this value (India) and then search the csv file's first column and if it matches, I need to send only those particular rows matching to the country name given from the cmd to the script.
I thought of using If Controller but how can I check the csv files first row and when there is a match, send those details to the script.
The easiest option would be dynamically generating a CSV file with only India lines
Add setUp Thread Group to your Test Plan
Add Test Action sampler to the setUp Thread Group (this way you won't have an extra result in .jtl file)
Add JSR223 PreProcessor as a child of the Test Action Sampler
Put the following code into "Script" area:
String country = props.get('Country')
def originalCsvFile = new File('C:/Users/Dev/Desktop/JI/JVMDetails/Details.txt')
def countryCsvFile = new File('C:/Users/Dev/Desktop/JI/JVMDetails/Country.txt')
countryCsvFile.delete()
originalCsvFile.eachLine {line ->
if (line.startsWith(country)) {
countryCsvFile << line
countryCsvFile << System.getProperty('line.separator')
}
}
Configure your CSV Data Set Config to use C:\Users\Dev\Desktop\JI\JVMDetails\Country.txt as this file will have only those lines which start with what you have defined as Country property
More information:
Apache Groovy - Why and How You Should Use It
Groovy Goodness: Working with Files
You need to loop through CSV, see example or other examples.
As the second example use in while condition the variable from CSV: ${Country} .
Inside loop you need to add If Controller with condition to compare country variable against country property:
${__jexl3("${__P{Country}" == "${Country}")}
Checking this and using __jexl3 or __groovy function in Condition is advised for performances

How can I check if a table or view exists in Oracle DB using javascript?

I need to check if a table name from html input exists in an oracle database, how can I do that?
You cannot access a db from client side (javascript browser). You need to expose, server side, a service which accepts in the GET call a parameter string, the table name, and call this server with an ajax call client side, using javascript and sending the required table name string into the GET body of the ajax call.
The server will receive the table name, check it against its db wit a proper query, then return the result to the client that will parse the server result as GET return value and perform the desired action
EDIT: answering to the comment, you need to query your db searching for your table, let's say named your-table-name, in your db user_tables executing the following query via php:
SELECT table_name FROM user_tables where table_name = 'your-table-name'
and then check if the query returns one record (the table exists) or none (the table doesn't exist).

command line argument to a javascript file that works on mongodb

I have a javascript file ( .js ) that works on MongoDB. I run the .js file as
mongo localhost:27017/dbname myjsfile.js .
How can I send command line arguments while running this JavaScript file ? I want to send database name and collection name as command line argument.
Well, you are already setting the database in use as you connect via:
mongo localhost:27017/dbname
So it is now on database "dbname". That is carried through to the db variable. Which is just a placeholder for the "current" database object.
That means that anything in your "script":
var results = db.collection.find().toArray();
For example is using the database you selected and the collection you named.
Need more? This is valid to:
db["mycollection"].find();
It's just JavaScript to the shell.
if you want a collection to be set as a variable then do something like this:
mongo localhost/mydb --eval "var users = db.users" myfile.js
Or otherwise just do that in you JavaScript file. You can test that by:
mongo localhost/mydb --eval "var users = db.users" --shell
And in the shell you now have a variable users that is "aliased" to the users collection.
cli argument no. But you can read a json file and parse it in your script.
// config.json - {"dbname":"dbname","collection":"mycollection"}
var args = JSON.parse(cat("config.json"));

SQL.js in javascript

I want to store data in a SQLite database directly from a javascript script. I found this SQL.js library that is a port for javascript. However, apparently it's only available for coffeescript. Does anyone know how to use it in javascript? Other ideas about how to store data in SQLite DB are welcomed too.
Update
sql.js now has its own github organisation, where both the original author and I are members: https://github.com/sql-js/sql.js/ .
The API itself itself is now written in javascript.
Original answer
I am the author of this port of the latest version of sqlite to javascript: https://github.com/lovasoa/sql.js
It is based on the one you mentioned (https://github.com/kripken/sql.js), but includes many improvements, including a full documentation: http://lovasoa.github.io/sql.js/documentation/
Here is an example of how to use this version of sql.js
<script src='js/sql.js'></script>
<script>
//Create the database
var db = new SQL.Database();
// Run a query without reading the results
db.run("CREATE TABLE test (col1, col2);");
// Insert two rows: (1,111) and (2,222)
db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);
// Prepare a statement
var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}
// Bind new values
stmt.bind({$start:1, $end:2});
while(stmt.step()) { //
var row = stmt.getAsObject();
// [...] do something with the row of result
}
</script>
I'm using SQL.js from pure JavaScript without any problems. Simply include the following file:
https://cdnjs.com/libraries/sql.js

Categories