I have an problem using powershell .
first i would like to explain what the sitiation is :
I have an Oracle database running with an table NAMES . In the table i got about 10000 rows with data . I would like to to count them til 100 rows and and then "echo " them on my powershell prompt here is where the problem comes in because i can count the rows using the following script:
$query = “SELECT * FROM NAMES"
$command = $con.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$test= $result|Measure-Object
$i=$test.Count
The number that returns is the correct number but then it goes wrong because when i want to use an foreach loop i cant get the names from my table
Here is wat i got maybey it helps
foreach ($Row in $query.Tables[0].Rows)
{
write-host "value is : $($Row[0])"
}
hope someone finds an answer
You are missing the strict mode: Set-StrictMode -Version latest. By setting it, you'd get much more informative an error message:
$query = "SELECT * FROM NAMES"
foreach ($Row in $query.Tables[0].Rows) { ... }
Property 'Tables' cannot be found on this object. Make sure that it exists.
+ foreach ($Row in $query.Tables[0].Rows) { ... }
The $query variable doesn't contain member Tables, so attempting to read it is futile. It would seem likely that the $result variable contains the Tables member. That depends on the data provider you are using and what's missing on the code sample.
Related
Right to the point.
I need to update a field in the database using the field to calculate the new value first.
E.g of fields: https://i.stack.imgur.com/FADH6.jpg
Now I am using the Joomla updateObject function. my goal is to take the "spent" value from the DB table without using a select statement.
Then I need to calculate a new value with it like (spent + 10.00) and update the field with the new value. Check out the code below:
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($object->spent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The bit which i need to make the calculation on is
$object->spent = ($object->spent - $item['total']);
I realise I can use a seperate insert statement but I am wondering if there is a better way. Any help is much appreciated.
It needs to work like this, WITHOUT THE SELECT (working example)
$query = $db->getQuery(true);
$query->select($db->quoteName('spent'));
$query->from($db->quoteName('#__mytable'));
$query->where($db->quoteName('catid')." = ". $item['category']);
// Reset the query using our newly populated query object.
$db->setQuery($query);
$oldspent = $db->loadResult();
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($oldspent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
The sticking point with trying to use updateObject('#__mytable', $object, 'catid'); is that your query logic needs to reference the column name in the calculation to assign the "difference" as the new value. The raw mysql query syntax to update a column value with the value minus another value is like:
"`spent` = `spent` - {$item['total']}"
updateObject() will convert spent - {$item['total']} to a literal string, the database will expect a numeric value, so UPDATE results in a 0 value recorded. In other words, $db->getAffectedRows() will give you a positive count and there will be no errors generated, but you don't get the desired mathematical action.
The workaround is to discard updateObject() as a tool and build an UPDATE query without objects -- don't worry it's not too convoluted. I'll build in some diagnostics and failure checking, but you can remove whatever parts that you wish.
I have tested the following code to be successful on my localhost:
$db = JFactory::getDBO();
try {
$query = $db->getQuery(true)
->update($db->quoteName('#__mytable'))
->set($db->quoteName("price") . " = " . $db->qn("price") . " - " . (int)$item['total'])
->where($db->quoteName("catid") . " = " . (int)$item['category']);
echo $query->dump(); // see the generated query (but don't show to public)
$db->setQuery($query);
$db->execute();
if ($affrows = $db->getAffectedRows()) {
JFactory::getApplication()->enqueueMessage("Updated. Affected Rows: $affrows", 'success');
} else {
JFactory::getApplication()->enqueueMessage("Logic Error", 'error');
}
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage("Query Syntax Error: " . $e->getMessage(), 'error'); // never show getMessage() to public
}
Here is a StackOverflow page discussing the mysql subtraction logic: update a column by subtracting a value
I am trying to read a table in Oracle from PowerShell and want to save them in an ArrayList. The connection is working but reading the any rows after the first doesn't work.
Here's what I'm trying to do.
$rows = New-Object System.Collections.ArrayList
class Table {
[String] $name
[String] $type
}
try {
$oraConn.Open()
$sql = [string]::Format("select name, type from source_table where type = 'running'")
$oraCmd = New-Object System.Data.OracleClient.OracleCommand($sql, $oraConn)
$reader = $oraCmd.ExecuteReader()
#add tables to arraylist
while ($reader.Read()) {
$table = New-Object Table
$table.name = $reader["name"];
$table.type = $reader["type"];
[void]$rows.Add($table)
}
Write-Host "rows collected"
}
My problem is, I only read the first row of the table, how can I tell Oracle to read them all? Would I have to countthem first and then query for each row?
I check the contents of $rows later in the code, it's not really relevant to the question since I know that this part works, so I left it out.
I know that my query returns something because I tried it in Oracle.
Do I need a foreach loop? It would make sense but how can I tell Oracle to do that? Would I have to query for each row of the table and set a counter to query only one row at a time?
I hope someone can help me and point me in the right direction, since I'm already trying a long time to get my script working. I got most of the logic for my script, but if I can't load the rows into my list, my logic doesn't help me at all.
Use the following code snippet as a some base for an own solution:
$cs = 'data source=oradb;user id=/;dba privilege=sysdba'
$oc = new-object oracle.dataaccess.client.oracleconnection $cs
$oc.open()
$cm = new-object oracle.dataaccess.client.oraclecommand
$cm.connection = $oc
$cm.commandtext = "select name, type from source_table where type = 'running'"
$da = new-object oracle.dataaccess.client.oracledataadapter
$da.selectcommand = $cm
$tbl = new-object data.datatable
$da.fill($tbl)
$tbl | %{"$($_.name = $_.type)"}
I am new here I tried to find my problem here but I couldnt.
I have 2 db and I am searching two different information and comparing them. I thought many other languages which we called "containts"
I need to find which names rapor_one has and rapor_two does not have. Probably I have problem with Contains part. How can I Use it
for($i=1; $i -le $rapor_one.Rows.Count;$i++ ){
if($rapor_two.Contains($row)){
Write-Host $row
}
}
If it matters I am using connection string and connection adapter which I am also adding below
$connectionString =
$connection =
$connection.ConnectionString =
$connection.Open()
$command =
$command.CommandText =
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $
$Dataset = new-object System.Data.Dataset
$DataAdapter.Fill($Dataset)
I am sure my query working well I take db response but I just have problem with comparing them
****ADDED: Also I want to ask that if there was 2 or more attributes in my variable how can I compare them?
****ADDED:
This algorithm is better. Cant we use contains any other modern languages(I know we have in C# java etc?
foreach($row in $rapor_two)
{
if ($rapor_one - Contains $row){
Write-Host "True"
}
}
I have a query in laravel:
...
$query = $model::group_by($model->table().'.'.$model::$key);
$selects = array(DB::raw($model->table().'.'.$model::$key));
...
$rows = $query->distinct()->get($selects);
this works fine and gives me the fields keys' that I need but the problem is that I need to get all the columns and not just the Key.
using this:
$selects = array(DB::raw($model->table().'.'.$model::$key), DB::raw($model->table().'.*'));
is not an option, cuz it's not working with PostgreSQL, so i used $rows to get the rest of columns:
for ($i = 0; $i<count($rows); $i++)
{
$rows[$i] = $model::find($rows[$i]->key);
}
but as you see this is it's so inefficient, so what can i do to make it faster and more efficient?
you can find the whole code here: https://gist.github.com/neo13/5390091
ps. I whould use join but I don't know how?
Just don't pass anything in to get() and it will return all the columns. Also the key is presumably unique in the table so I don't exactly understand why you need to do the group by.
$models = $model::group_by( $model->table() . '.'. $model::$key )->get();
can i get the keys and values dynamically.
in php, you would: foreach ($array as $key => $value)
but you can do this for :
$this->_em->getRepository('Members')->findBy(array('id' =>5));
any way to get the keys from this with their values..?
i can do this by turning it into an array and extract it but i wouldnt get any association results inside the array ..
i want to do this as i want to be able to extract all properties and values of this object and extract all other objects within it too..
Ih had the same issue as you now have and after some research i just found a solution which you might be interested.what you need is an associative array of keys/values and not an object.findBy()method only returns entity OBJECT.so you will need to use DQL(doctrine query language).
//create a QueryBuilder instance
$qb = $this->_em->createQueryBuilder();
$qb->add('select', 'a')
//enter the table you want to query
->add('from', 'Members a')
->add('where', 'a.id = :id')
//order by username if you like
//->add('orderBy', 'a.username ASC')
//find a row with id=5
->setParameter('id', '5');
query = $qb->getQuery();
//if you dont put 3 or Query::HYDRATE_ARRAY inside getResult() an object is returned and if you put 3 an array is returned
$accounts = $query->getResult(3);
from doctrine documentation:
13.7.4. Hydration Modes
Each of the Hydration Modes makes assumptions about how the result is
returned to user land. You should know about all the details to make
best use of the different result formats:
The constants for the different hydration modes are:
Query::HYDRATE_OBJECT
Query::HYDRATE_ARRAY
Query::HYDRATE_SCALAR
Query::HYDRATE_SINGLE_SCALAR
To learn more about 'The Query Builder' please refer to doctrine2 documentation
Update:
To fetch associated Entities you will need to define fetch joins.Here is an example provided in doctrine documentation:
$dql = "SELECT b, e, r, p FROM Bug b JOIN b.engineer e ".
"JOIN b.reporter r JOIN b.products p ORDER BY b.created DESC";
$query = $entityManager->createQuery($dql);
$bugs = $query->getArrayResult();
foreach ($bugs AS $bug) {
echo $bug['description'] . " - " . $bug['created']->format('d.m.Y')."\n";
echo " Reported by: ".$bug['reporter']['name']."\n";
echo " Assigned to: ".$bug['engineer']['name']."\n";
foreach($bug['products'] AS $product) {
echo " Platform: ".$product['name']."\n";}
echo "\n";}
The code mentioned above will fetch your entities as array of arrays and you can do whatever you want with $keys and $values.
Hope this helps...