Forum Discussion
connect to mysql using reusable functions
Although I'm not sure I understood your last point 🙂 (defining a $Command variable globally)
No problem!
I just meant defining $Command using the $global prefix, so it'd look like:
$global:Command
That would allow you to use it anywhere within the script, including any functions. It just means - like the $global:Connection example - that you only have to create object once rather than every time you call a function.
So, that'd be two global variables:
- $global:Connection
- $global:Command
That would allow you to create them once but use them many times, which makes your script that little bit faster/efficient (particularly over larger data sets.)
Cheers,
Lain
- John_DodoJun 08, 2022Brass Contributor
Do you mean this section?
$MYSQLCommand = New-Object MySql.Data.MySqlClient.MySqlCommand $MYSQLDataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter $MYSQLDataSet = New-Object System.Data.DataSetI would take it out of the Runquery() function and I define it in the main screen then? (adding $global: in front of each lines)
Doing so these lines are read only once instead of every Runquery calls. I am right?
- LainRobertsonJun 08, 2022Silver Contributor
- John_DodoJun 09, 2022Brass Contributor
Thank you Lain for your help,
Please excuse this "off-topic" question that might pollute the thread :
In this script my source CSV has about 4000 records, so I will run my query 4000 times.
My script duration is 1 min, which is very ok to me.
But speaking about best pratices, would you recommand that I load the whole table content once in a variable and then search in that variable for my records? Instead of running my query everytime for each record.
I suppose it depends on the size of the table of course, but generaly speaking, what do you think is best?
thanks