completion of jmeter execution generate the csv file ,how read the csv file in groovy and how to automaticaly pass those values in query ?, ?,? places [duplicate] - mysql

Please give step by step process
How to connect MySQL db and excute queries and stored those results in db table by using jsr223 sampler? Please give sample code this topic

Download MySQL JDBC Driver and drop it to "lib" folder of your JMeter installation (or other folder in JMeter Classpath)
Restart JMeter to pick up the .jar
Add Thread Group to your Test Plan
Add JSR223 Sampler to your Thread Group
Put the following code into "Script" area:
import groovy.sql.Sql
def url = 'jdbc:mysql://your-database-host:your-database-port/your-database-name'
def user = 'your-username'
def password = 'your-password'
def driver = 'com.mysql.cj.jdbc.Driver'
def sql = Sql.newInstance(url, user, password, driver)
def query= 'INSERT INTO your-table-name (your-first-column, your-second-column) VALUES (?,?)'
def params = ['your-first-value', 'your-second-value']
sql.executeInsert query, params
sql.close()
Change your-database-host, your-database-port, etc. to real IP address, port, credentials, table name, column name, etc.
Enjoy.
More information:
Apache Groovy - Working with a relational database
Apache Groovy - Why and How You Should Use It
P.S. I believe using JDBC Request sampler would be way faster and easier

Related

AssertionError: DatabaseBackend is not running

In FastAPI, I need to dynamically connect to a database after a POST request, i.e, in the POST request body, I receive database_name on which I need to connect.
So I have tried this:
import databases
#app.post("/computers/", response_model=Computer)
async def create_computer(computer: ComputerIn):
DATABASE_URL = "postgresql://username:password#localhost/"+computer.database_name
database = databases.Database(DATABASE_URL)
database.connect()
...
But I get the following error:
File
"/home/.local/lib/python3.8/site-packages/databases/backends/postgres.py",
line 169, in acquire
assert self._database._pool is not None, "DatabaseBackend is not running" AssertionError: DatabaseBackend is not running
Any idea why this might not work ?
Thanks
Two things:
You forgot the await keyword. Here's an example taken from the github's page https://github.com/encode/databases
# Create a database instance, and connect to it.
from databases import Database
database = Database('sqlite+aiosqlite:///example.db')
await database.connect()
# Create a table.
query = """CREATE TABLE HighScores (id INTEGER PRIMARY KEY, name VARCHAR(100), score INTEGER)"""
await database.execute(query=query)
It is not good practice to connect to a database on every request. It is better to connect at runtime and then share the connection pool, so that at every request a new connection is not create. Instead, the currently active connection pool is used, wasting fewer resource.
See https://fastapi.tiangolo.com/advanced/events/ for further information

How do you setup a MySQL connection for Orange?

Has anyone ever setup a SQL connection for Orange? The API (https://docs.biolab.si//3/data-mining-library/reference/data.sql.html) does not provide any decent examples, from my read of things. If you could point me to a link or show me an example connection object in Python, that would be great. I am trying to do some CN2 classification on a table in my MySQL database.
It is possible using a ODBC connector:
from pyodbc import connect
connector = connect('Driver={MySQL ODBC 5.3 Unicode Driver};'
'Server=server name or IP;'
'Database=database name;'
'UID=User;'
'PWD=password;')
cursor = connector.cursor() # Creation of the cursor for data swept.
# Execution of the SQL Query.
cursor.execute("SELECT id, data1, data2 FROM table1")
# All data of "table1" are saved in "data".
data = cursor.fetchall()

SQLAlchemy core -How do I access an existing Postgresql database?

I have created the below class
This seems to give me access to the schema of the table but not to the table itself. Most of the examples I am seeing, including the one in the manual follow the code that was used to create the tables
class DataBase:
def __init__(self,user, password, db, host='localhost', port=5432):
'''Initializes the connection and a metadata objects'''
# We connect with the help of the PostgreSQL URL
# postgresql://federer:grandestslam#localhost:5432/tennis
url = 'postgresql://{}:{}#{}:{}/{}'
url = url.format(user, password, host, port, db)
# The return value of create_engine() is our connection object
self.engine = sqlalchemy.create_engine(url, client_encoding='utf8', echo=False) #echo=True enable logging (This is Python loggin module)
self.conn=self.engine.connect()
# We then bind the connection to MetaData()
self.meta = sqlalchemy.MetaData(bind=self.con, reflect=True)
And then I use
if __name__ == '__main__':
db=DataBase('nme','nme','nme')
db.meta.tables['tablename']
But this is giving me access to the schema of the table
I want to insert a record in this table after the table was created
Edit: this worked, thank you
known_devices=Table('known_devices',self.meta,autoload=True)
ins=known_devices.insert().values(
....
)
result=self.conn.execute(ins)
Looking at
https://docs.sqlalchemy.org/en/latest/core/reflection.html and
https://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.Insert.values
it should be something along the lines of
yourtable=Table('tablename', meta, autoload=True)
conn.execute(yourtable.insert(), field="content")

How can I connect to a MySQL database into Apache Spark using SparkR?

I am working on Spark 2.0 and SparkR libs. I want to get a sample code on how can I do following things in SparkR?
Connect to a MySQL or any other SQL database using SparkR.
Write SQL queries like SELECT , UPDATE etc. to modify a table in that database.
I know to do it using R. However I would need some help to use Spark Sessions or SparkSQL context. I am using R Studio for the development.
Moreover, how do we submit this R code as Spark Batch to run continuously at a regular intervals?
jdbcurl <- "jdbc:mysql://xxx.xxx.x.x:xxxx/database"
data <- read.jdbc(jdbcurl, "tablename", user = "user", password = "password" )

Grails create the mysql table during startup

I am trying to create the sample table data during start-up. I have the below code in my BootStrap.groovy file.
But Sql.newInstance giving the exception.
how can I run the mysqldump script during startup?
println "developmnet creating table"
String sqlString = servletContext.getResourceAsStream("/data/table_dump.sql").text
def db = [url:grailsApplication.config.dataSource.url, user:grailsApplication.config.dataSource.username, password:grailsApplication.config.dataSource.password, driver:grailsApplication.config.dataSource.driverClassName]
println "DataBase"+ db
def cls = Class.forName(db.driver).newInstance();
Sql sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
sql.execute(sqlString)
Try to take a look at Grails Database Migration Plugin. It provides a good approach to manage migration scripts and database state management.