Powershell insert into MS Access with WHERE clause - sql

Trying to insert values into MS Access DB based on values entered into a powershell form with a WHERE clause. I'm receiving a simple error but struggling to resolve ("Missing Semicolon (;) at end of SQL Statement")
Here is my base code;
$query = "INSERT INTO SignIns ([DateTimeOUT], [SignedOut]) VALUES ('$($info.F1)','$($info.F2)') FROM $Info WHERE SignIns.Surname = '$($Info.F3)'"
$cmd = $conn.CreateCommand()
$cmd.CommandText = $query
$result = $cmd.ExecuteNonQuery()
$conn.Close()
I've amended to add a semicolon in all places I thought could resolve, but no luck, still returns the same error (Missing Semi Colon at end of SQL statement);
$query = "INSERT INTO SignIns ([DateTimeOUT], [SignedOut]) VALUES ('$($info.F1)','$($info.F2)') FROM $Info WHERE SignIns.Surname = '$($Info.F3);';";
$cmd = $conn.CreateCommand()
$cmd.CommandText = $query;
$result = $cmd.ExecuteNonQuery();
$conn.Close()
(for reference, I've added a semi-colon at the end of my WHERE clause, at the end of the $Query variable and tried to append onto the end of $query when executing in the $cmd.commandtext variable, and also on the end of the $result variable.
I expect the statement to execute as normal and update with the given values. Testing within Access DB itself is difficult as I am unable to reference my PS form from within the DB. Any help greatly appreciated,
Thanks.

Update: Ameding query to UPDATE now lets me 'insert' values with WHERE statement following a simple logic.
$conn.Open()
$query = "UPDATE SignIns SET DateTimeOUT = '$($info.F1)' WHERE SignIns.Surname = '$($Info.F3)'";
$cmd = $conn.CreateCommand()
$cmd.CommandText = $query;
$result = $cmd.ExecuteNonQuery();
$query = "UPDATE SignIns SET SignedOut = '$($info.F2)' WHERE SignIns.Surname = '$($Info.F3)'";
$cmd = $conn.CreateCommand()
$cmd.CommandText = $query;
$result = $cmd.ExecuteNonQuery();
$conn.Close()
It is not a method I'm normally use to when inputting new values into a table, but same result so.. I don't think there's any implications. It probably takes the update as 'Update from NULL to VALUE' as opposed to INSERT FROM source to DESINTATION (where)

Related

Oracle SQL query returns some data when it should be empty-PowerShell

I am writing a script in PowerShell Core 7.2. I get a list of files from a folder that I check against Oracle db. I need the data of Description, and NC_Name column if the file is in db.
The issue is that even when the file is not in db it still returns the data but of some other file.
For example: I have a list of files, File#1, File#2,File#3. If File#2 is not in the db it still returns the data of File#1.
I have tried counting the number of rows and putting it as a condition. As in
$rowNum = $connection.count
The issue with this is that $rowNum is never zero because it returns data for some other file; because the variable $fileName is never empty.
I also tried checking for the file name in the query itself but it gave a lot of errors. The query was
$query="DECLARE record_exists INTEGER; BEGIN SELECT COUNT(*) INTO record_exists FROM NC_PROGRAMS WHERE NC_PROGRAMS.NC_NAME = '$fileName' AND ROWNUM = 1; IF record_exists = 1 THEN Select DESCRIPTION, NC_NAME"
The code is:
#Get all files
$result = $start.EnumerateDirectories() | ForEach-Object -Parallel {
$_.GetFiles('*.EIA', $using:enum)
}
$result | Format-Table -AutoSize
foreach($item in $result){
$fileName = $item.BaseName
#Oracle connection
Add-Type -Path C:\lib\netstandard2.1\Oracle.ManagedDataAccess.dll
$query = "Select DESCRIPTION, NC_NAME From NC_PROGRAMS WHERE
NC_PROGRAMS.NC_NAME = '$fileName' "
$connectionString = "connectionString"
$connection = New-Object Oracle.ManagedDataAccess.Client.OracleConnection($connectionString)
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
$reader = $command.ExecuteReader()
$rowNum = $connection.count
Write-host "Number of rows-"$rowNum
while($reader.Read()) {
$description=$reader.GetString(0)
$fastemsFileName = $reader.GetString(1)
}
$connection.Close()
}

Importing CSV columns into SQL table without Sqlcmd

I’m currently importing a csv file and inserting some of the results into a table.
Unfortunately I’m using Sqlcmd, but the module isn’t installed on the relevant server and can’t be installed (out of my control).
Is there a way to manage the exact same as the below, outside of SqlCMD?
Example Code:
$server = 's'
$database = 'd'
$table = 't'
Import-CSV C:\Test\Test.csv | ForEach-Object {Invoke-Sqlcmd `
-Database $database -ServerInstance $server `
-Query "INSERT INTO $table VALUES ('$($_."Column One")',
'$($_."Column Two")',
NULL,
'$($_.""Column Three"")')"
}
You can try the ADO.Net objects:
# Hardcode the table name, unless you *REALLY* trust your users.
$SQL = "INSERT INTO TableName VALUES (#Column1, #Column2, NULL, #Column3)"
$conn = new-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=$server;Database=$database;Integrated Security=True;"
$cmd = new-Object System.Data.SqlClient.SqlCommand($SQL, $conn)
# Use actual types and lengths from the database here
$c1 = $cmd.Parameters.Add("#Column1", [System.Data.SqlDbType]::NVarChar, 20)
$c2 = $cmd.Parameters.Add("#Column2", [System.Data.SqlDbType]::NVarChar, 20)
$c3 = $cmd.Parameters.Add("#Column3", [System.Data.SqlDbType]::NVarChar, 20)
$conn.Open()
Import-CSV C:\Test\Test.csv | ForEach-Object {
$c1.Value = $_."Column One"
$c2.Value = $_."Column Two"
$c3.Value = $_."Column Three"
$cmd.ExecuteNonQuery()
}
$conn.Close()
This will also fix any issues with apostrophes in the data, which would have caused HUGE problems in the original.
You could try and use the bulk insert command, search for a simple SQL connection and query execution - the exact one that Joel Coehoorn posted, if you have bulk permissions and the server has access to the file itself. you could also add parameters to it and then call it however you see fit. Meaning you could foreach files in folder, call the bulk insert with your connection.
BULK INSERT TableName
FROM 'LinkToSourceFile.csv' WITH (
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n',
FIRSTROW = 2
);

Sql query result as an array of objects powershell

I'm trying to operate with the result of this query to then run an update query on specific values of the result. What i'm trying to do is to get all the values from the table and then check if those values are between 1 and 5 and turn those to null. Since i can't do this in one update query, i'm doing first a select and then operate on the singular values that i get from the result, but the query returns me a dataset result which i can't operate with in PowerShell (or at least i don't know how). What can i do? The main objective of this should be an update to all the columns of the table on the db to change the columns with values between 1 and 5 and turn them into null values
Here is the code:
$SQLServer = "Server\SQLEXPRESS"
$SQLDBName = "Prova"
$SqlQuery = "Select * from table_2 where id=1"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; trusted_connection=true;"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter.SelectCommand = $SqlCmd
$Dataset = New-Object System.Data.DataSet
$SqlAdapter.Fill($Dataset)
$array=$Dataset.Tables[0]
$SqlConnection.Close()
A fellow few-months old newbie here(me), ill try to give this a shot!
You can actually loop through the rows of the dataset you have, and access the properties (columns) in those rows, modify it and then dynamically create an update statement and execute it on your server.
The main part is presented below, the rest are just the functions i defined myself. Not sure if this is what you had in mind but my testing setup went something like this. (Note please execute/define the functions first in your powershell session before you run the code below)
# SET VARIABLES
$Serv = <Your Server>
$DB = <Your DB>
$TSQL = "SELECT * FROM TestTBL"
# Target Results table from SQL
$MainResultsTable = (GetSQLData $Serv $DB $TSQL).Tables[0]
#Get Column names
$Colnames = ($MainResultsTable.Rows | gm -MemberType NoteProperty,Property).Name
# Loop through each row of data from SQL results
foreach($row in $MainResultsTable.Rows)
{
# Construct the TSQL update statement. Using an array to construct the multi column updates.
$TSQLUpdate = "UPDATE TestTBL SET "
$TSQLUpdateArr =#()
foreach($Col in $Colnames)
{
# We don't need to update the ID
if($Col -ne 'ID')
{
$TSQLUpdateArr += "$Col = $(EvaluateColumnData $row.$Col)`n"
}
}
# join the columns with the corresponding end of TSQL where the target ID is specified
$TSQLUpdate += $($TSQLUpdateArr -join ",").ToString() + " WHERE ID = $($row.ID);"
# Execute the update on SQL server
UpdateSQL $Serv $DB $TSQLUpdate
}
Putting a few snippets of the functions I wrote for SQL here too. [Open to optimization and critics to make this faster or more 'semanticy']
# Define custom user function to set the values to be used for updating
function EvaluateColumnData()
{
param( $data )
if($data -le 5){ return "NULL" }
else { return $data }
}
# Get data from SQL
function GetSQLData()
{
param( $tgtServ,$tgtDB,$tgtTSQL )
# Create connection obj
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "server="+$tgtServ+";database="+$tgtDB+";trusted_connection=true;"
# Open SQL connection
$SqlConnection.open()
# Create TSQL CMD object and pass the connection object
$SQLCommand = New-Object System.Data.SQLClient.SQLCommand
$SQLCommand.Connection = $SqlConnection
# TSQL statement to be executed
$SQLCommand.CommandText = $tgtTSQL
$SQLCommand.CommandTimeOut = 0
# Container/adapter for SQL result
$resultAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($SQLCommand)
# DataSet where the results are dumped
$resultDS = New-Object System.Data.DataSet
$resultAdapter.Fill($resultDS) | Out-Null
$SqlConnection.Close()
return ,$resultDS
}
# Execute TSQL statement without results
function UpdateSQL()
{
Param( $tgtServ,$tgtDB,$tgtTSQL )
$ServerConn = New-Object System.Data.SQLClient.SQLConnection
$ServerConn.ConnectionString = "server="+$tgtServ+";database="+$tgtDB+";trusted_connection=true;"
$ServerConn.Open()
$ServerCMD = New-Object System.Data.SQLClient.SQLCommand
$ServerCMD.Connection = $ServerConn
$ServerCMD.CommandText = $tgtTSQL
$ServerCMD.CommandTimeOut = 0
$ServerCMD.ExecuteNonQuery() | out-null
$ServerConn.Close()
}
Hope this helps. There are a lot of things out there you can read(which im still reading lol) which offers better explanation, I suggest focusing on the basics.
Recommended reading: DataTables, PS objects/Custom objects, hashtable, Functions.

PowerShell script to query xml tag attribute in database

I want to write a query in powerShell which checks an attribute value in an xml column called(xml_multiple) and return boolean value 1 if it exist(otherwise 0) and pass it to a variable and call a sendemail function.
According to the value of variable the email will be sent.
1- for success
0- for failure
I'm new to powershell and not very good at it. I'm open to suggestion as long it works.Thanks in advance. Check the code below and xml
$dataSource = "DB.abc.com"
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$query = “ ” <#here i want to write my query#>
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object “System.Data.DataTable”
$table.Load($result)
$connection.Close()
function sendemail()
{
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "abc#xyz.com"
if ($send -eq 1) <#here i want to pass value from db#>
{
$Mail.Subject = "Process Successful"
$Mail.Body ="Success`n`nThank you"
}
else
{
$Mail.Subject = "Process Unsuccessful"
$Mail.Body ="Unsuccess`n`nPlease look into it"
}
$Mail.Send()
}
Note: This is the xml and if any xml has a attribute start="1" return 1 else 0. for a particular day(There will be only one record in a day which will have this attribute,so we can use a filter in the query for that)
<jobparameters start="1">
<work>1
</work>
</jobparameters>
P
lease give suggestions
It is possible to get the needed results directly from SQL Server:
DECLARE #x XML = '
<jobparameters start="1">
<work>1
</work>
</jobparameters>';
DECLARE #t TABLE (xml_multiple XML);
INSERT #t(xml_multiple) VALUES(#x);
SELECT c.value('#start','INT') send
FROM #t
OUTER APPLY xml_multiple.nodes('/jobparameters')x(c);

PDO SQL - Update query issue

I am new to pdo and do not get why the following insert query does not work. If I remove the line that executes the query, there will be of course no insertion, but there will be no error. If I leave that line, the script is not executed. Of course I checked and rechecked the table name and field name. Hope someone can hep me understand. Note that before executing the query, the ber_mBacth_date field of my table is set to NULL. Cheers. Marc
<?php
$db_host = 'localhost';
$db_user = 'user';
$db_password = 'user';
$db_database = 'myconsole';
$mBatchDate = date('Y-m-d H:i:s');
$connexion = new PDO("mysql:host=$db_host;dbname=$db_database", $db_user, $db_password);
$qry = $connexion->execute('UPDATE batcherrors SET ber_mBatch_date = "'.$mBatchDate.'"');
$connexion = NULL;
?>
Can you try instead of:
$connexion = new PDO("mysql:host=$db_host;dbname=$db_database", $db_user, $db_password);
$qry = $connexion->execute('UPDATE batcherrors SET ber_mBatch_date = "'.$mBatchDate.'"');
do:
$statement = $connexion->prepare("UPDATE batcherrors SET ber_mBatch_date = :mBatchDate");
$statement->bindValue(':mBatchDate', $mBatchDate, PDO::PARAM_STR);
$statement->execute();
Binding is recommended way to set parameters values (over concatenation).