.Net methods that throw bad errors.

Status
Not open for further replies.
So I'm working in Powershell (yeah, bringing my Powershell questions over here because we have long left the realm of system administration) and trying to mass modify Access databases. After much questing, I have found how to query Access databases in Powershell.

Code:
$conn = new-object data.odbc.odbcconnection
    $conn.ConnectionString = "dsn=$connectionname"
    $conn.open()
    
    $query1 = "select * from known_good_table where known_good_field = `"" + $myobject.SomeValue + "`""
    write-host $query1
    $cmd1 = $conn.CreateCommand()
    $cmd1.CommandText = $query1
    $data1 = $cmd1.ExecuteReader()
    $result1 = new-object "System.Data.DataTable"
    $result1.Load($data1)

I've had to chop up a bunch of the code so it obviously wouldn't just work if you copy/pasted it. In any case, here's the deal. This code works when my query is simply "select * from known_good_table" So something's wrong with my query, right? Right. Wrong. Query's fine. You see there I'm outputting $query1, and I copy that output directly in to Access and it works as expected. Same thing when I output $cmd1.CommandText, just to make sure something didn't get beat up in translation.

The exact error I'm getting is,

Code:
Exception calling "ExecuteReader" with "0" argument(s): "ERROR [07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1."
At D:\My\Path\MyScript.ps1:39 char:5
+     $data1 = $cmd1.ExecuteReader()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : OdbcException
 
Exception calling "Load" with "1" argument(s): "Value cannot be null.
Parameter name: dataReader"
At D:\My\Path\MyScript.ps1:41 char:5
+     $result1.Load($data1)
+     ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException

Value is very much not null. Best I can figure is something has a problem with the where clause in my query, but it's not Access. Oh, also the where clause will return data, so it's not an issue of it not handling no data returned (or at least it shouldn't be). Thoughts and opinions?
 
[url=http:/civis/viewtopic.php?p=28660839#p28660839:2ws2cqc4 said:
wallinbl[/url]":2ws2cqc4]It's telling you that $data1 is null (not an instance of an object), not that your query isn't returning results.

I'm not sure how you're coming to the conclusion that $data1 being null is the root of the problem, or what I should do about it. Could you expand on your thoughts a little more?

Because from where I sit, yes there is a message about $data1 being null. But the first message is about ExecuteReader not working properly. Since ExecuteReader is what populates $data1, I figure that's the place to start looking. The only thing that's making ExecuteReader not work properly is the fact that I put a where clause in the query.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
You need the full exception. Powershell (not .NET) is only showing you the "top" of the exception stack.

1) Use powershell_ise to edit the script

2) change the execute step to
Code:
try {
   $data1 = $cmd1.ExecuteReader()
} catch [System.Exception] {
   Write-Error "ExecuteReader failed: $_"
}

3) in powershell_ise, put a breakpoint on the line inside the catch block.

Run the code. When the breakpoint hits, explore $_ (the exception) in the command prompt within powershell_ise. Examples:
Code:
>  $_
>  $_.Message
>  $_.InnerException
>  $_.InnerException.InnerException.Message

If you can't use powershell_ise for some reason, just change the code inside the script block to be a bunch of these print statements and keep edit/running it until you get the info that tells you what's going on.
 
Sorry, I'm a little confused as to where Powershell ends and .Net begins. But here's the best of what I got out of the commands you gave me.

Code:
ERROR [07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
At D:\my\path\myscript.ps1:41 char:5
+     $data1 = $cmd1.ExecuteReader()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], OdbcException
    + FullyQualifiedErrorId : OdbcException

That was the result of doing $_ in the debug prompt. $_.Message, $_.InnerException, etc., do not exist.

Edit:
Forgot to get rid of names.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
Was that inside the catch block?

The message seems to think that there's a parameter expected in your query. Does your query have an "@" or a ":" in it?

Oh yeah, try
Code:
$_ | Get-Member
. Powershell might be wrapping the .Net Exception in another layer. Maybe $_.Exception?

Also, if you're doing it interactively in the ISE, you can just do $_.<Tab> and keep hitting Tab. It'll cycle through the fields/properties/methods on $_.

$_ is the "default variable", perl-style. Inside the catch block, it's should be set to the thing you just caught. When writing long-lasting script, I always reassign $_ to a meaningfully-named variable first thing.
 

krimhorn

Ars Legatus Legionis
39,865
Try not setting CommandText and instead passing in your SQL statement to ExecuteReader.

Looks like CommandText exists for legacy support to Excel and ExecuteReader does not have a method overload that will only read the CommandText property.

Code:
$conn = new-object data.odbc.odbcconnection
    $conn.ConnectionString = "dsn=$connectionname"
    $conn.open()
    
    $query1 = "select * from known_good_table where known_good_field = `"" + $myobject.SomeValue + "`""
    write-host $query1
    $cmd1 = $conn.CreateCommand()
    $data1 = $cmd1.ExecuteReader($query1)
    $result1 = new-object "System.Data.DataTable"
    $result1.Load($data1)
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
Looks like CommandText exists for legacy support to Excel and ExecuteReader does not have a method overload that will only read the CommandText property.
Pretty sure you read that wrong.

The Documentation":1828kebn said:
You should use the CommandText property instead of the SQL property, which now exists primarily for compatibility with earlier versions of Microsoft Excel. If you use both properties, the CommandText property's value takes precedence.
It's the "SQL" property that is deprecated.
 
[url=http:/civis/viewtopic.php?p=28661985#p28661985:1t1uwxxw said:
Pont[/url]":1t1uwxxw]Was that inside the catch block?

The message seems to think that there's a parameter expected in your query. Does your query have an "@" or a ":" in it?

Oh yeah, try
Code:
$_ | Get-Member
. Powershell might be wrapping the .Net Exception in another layer. Maybe $_.Exception?

Also, if you're doing it interactively in the ISE, you can just do $_.<Tab> and keep hitting Tab. It'll cycle through the fields/properties/methods on $_.

$_ is the "default variable", perl-style. Inside the catch block, it's should be set to the thing you just caught. When writing long-lasting script, I always reassign $_ to a meaningfully-named variable first thing.

Alright, sorry this has taken a while. But here's what I got. I commented out my ExecuteReader line, and copy/pasted your try/catch blocks. I put the breakpoint at the Write-Error line (inside the catch block, right?). Then I ran it in Powershell ISE. $_ gives the previously shown error. $_ | get-member shows...

Code:
   TypeName: System.Management.Automation.ErrorRecord

Name                  MemberType     Definition                                                                                                                      
----                  ----------     ----------                                                                                                                      
Equals                Method         bool Equals(System.Object obj)                                                                                                  
GetHashCode           Method         int GetHashCode()                                                                                                               
GetObjectData         Method         void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context...
GetType               Method         type GetType()                                                                                                                  
ToString              Method         string ToString()                                                                                                               
CategoryInfo          Property       System.Management.Automation.ErrorCategoryInfo CategoryInfo {get;}                                                              
ErrorDetails          Property       System.Management.Automation.ErrorDetails ErrorDetails {get;set;}                                                               
Exception             Property       System.Exception Exception {get;}                                                                                               
FullyQualifiedErrorId Property       string FullyQualifiedErrorId {get;}                                                                                             
InvocationInfo        Property       System.Management.Automation.InvocationInfo InvocationInfo {get;}                                                               
PipelineIterationInfo Property       System.Collections.ObjectModel.ReadOnlyCollection[int] PipelineIterationInfo {get;}                                             
ScriptStackTrace      Property       string ScriptStackTrace {get;}                                                                                                  
TargetObject          Property       System.Object TargetObject {get;}                                                                                               
PSMessageDetails      ScriptProperty System.Object PSMessageDetails {get=& { Set-StrictMode -Version 1; $this.Exception.InnerException.PSMessageDetails };}

I thought perhaps PSMessageDetails might but it's empty.
 

krimhorn

Ars Legatus Legionis
39,865
[url=http:/civis/viewtopic.php?p=28662953#p28662953:cr1v66sz said:
Pont[/url]":cr1v66sz]
Looks like CommandText exists for legacy support to Excel and ExecuteReader does not have a method overload that will only read the CommandText property.
Pretty sure you read that wrong.
Ahh, you're right. Was a quick lookup as I was leaving work.

Still, it looks like ExecuteReader doesn't appear to have a no parameter overload which is what the error he was getting seemed to be pointing to.

Edit: well, poking around with PS a bit on my home computer and I'm not so confident about the last. When I call an ExecuteReader on an odbcconnection object with no parameters I get the error

"Exception calling "ExecuteReader" with "0" arguments: ExecuteReader: CommandText property has not been initialized" which looks like it would imply that it does use CommandText if no argument is supplied (which makes sense as PS is simply wrapping the .NET object in a commandlet so it can define whatever process it wants so long as it gets the information that the .NET method requires).

Unfortunately I can't pursue this any further as I don't have a SQL Server instance at home and don't have SELECT permissions at work.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
Alright, sorry this has taken a while. But here's what I got. I commented out my ExecuteReader line, and copy/pasted your try/catch blocks. I put the breakpoint at the Write-Error line (inside the catch block, right?). Then I ran it in Powershell ISE. $_ gives the previously shown error. $_ | get-member shows...

So it looks like powershell is wrapping the error in a powershell-specific object. Try $_.Exception.ToString()

That said, this error you posted earlier
Code:
ERROR [07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
Suggests that it expects there to be a parameter in your SQL query. Every SQL language uses different placeholders for parameters and I don't remember which one Access-via-ODBC uses. Are there any "@", ":", or "?" in your SQL query?
 
No special characters in the query. At least none that should get passed through. I had a heck of a time getting Powershell to give me the output of $myobject.somevalue, rather than some kind of technical description of what $myobject was, which included an @ symbol. That's why I started writing the value of $query1, because I wanted to make sure that what was getting passed to Access was a valid query.

Also, I tried ending the query with a semicolon just in case it was being finicky about that. It was not.

Edit:
Also I suppose it would be helpful if I told you that the value I'm using for $myobject.somevalue is simply "Default" without the quotes of course. Nothing fancy yet. Just trying to get basic functionality nailed down, then I'll work on handling special characters in case someone wants to get cute.
 
So this may sound a little weird. But you know how in the new Windows Task Scheduler, you put in your command, and there's now a separate box for command line arguments? I wonder if the same sort of thing is going on here. Everything works without the where clause. The where clause gets added, and it mysteriously breaks. The question would be: Where else would you put such an argument?

Code:
   TypeName: System.Data.Odbc.OdbcCommand

Name                      MemberType Definition                                                                                                      
----                      ---------- ----------                                                                                                      
Disposed                  Event      System.EventHandler Disposed(System.Object, System.EventArgs)                                                   
Cancel                    Method     void Cancel(), void IDbCommand.Cancel()                                                                         
Clone                     Method     System.Object ICloneable.Clone()                                                                                
CreateObjRef              Method     System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)                                                 
CreateParameter           Method     System.Data.Odbc.OdbcParameter CreateParameter(), System.Data.IDbDataParameter IDbCommand.CreateParameter()     
Dispose                   Method     void Dispose(), void IDisposable.Dispose()                                                                      
Equals                    Method     bool Equals(System.Object obj)                                                                                  
ExecuteNonQuery           Method     int ExecuteNonQuery(), int IDbCommand.ExecuteNonQuery()                                                         
ExecuteNonQueryAsync      Method     System.Threading.Tasks.Task[int] ExecuteNonQueryAsync(), System.Threading.Tasks.Task[int] ExecuteNonQueryAsyn...
ExecuteReader             Method     System.Data.Odbc.OdbcDataReader ExecuteReader(), System.Data.Odbc.OdbcDataReader ExecuteReader(System.Data.Co...
ExecuteReaderAsync        Method     System.Threading.Tasks.Task[System.Data.Common.DbDataReader] ExecuteReaderAsync(), System.Threading.Tasks.Tas...
ExecuteScalar             Method     System.Object ExecuteScalar(), System.Object IDbCommand.ExecuteScalar()                                         
ExecuteScalarAsync        Method     System.Threading.Tasks.Task[System.Object] ExecuteScalarAsync(), System.Threading.Tasks.Task[System.Object] E...
GetHashCode               Method     int GetHashCode()                                                                                               
GetLifetimeService        Method     System.Object GetLifetimeService()                                                                              
GetType                   Method     type GetType()                                                                                                  
InitializeLifetimeService Method     System.Object InitializeLifetimeService()                                                                       
Prepare                   Method     void Prepare(), void IDbCommand.Prepare()                                                                       
ResetCommandTimeout       Method     void ResetCommandTimeout()                                                                                      
ToString                  Method     string ToString()                                                                                               
CommandText               Property   string CommandText {get;set;}                                                                                   
CommandTimeout            Property   int CommandTimeout {get;set;}                                                                                   
CommandType               Property   System.Data.CommandType CommandType {get;set;}                                                                  
Connection                Property   System.Data.Odbc.OdbcConnection Connection {get;set;}                                                           
Container                 Property   System.ComponentModel.IContainer Container {get;}                                                               
DesignTimeVisible         Property   bool DesignTimeVisible {get;set;}                                                                               
Parameters                Property   System.Data.Odbc.OdbcParameterCollection Parameters {get;}                                                      
Site                      Property   System.ComponentModel.ISite Site {get;set;}                                                                     
Transaction               Property   System.Data.Odbc.OdbcTransaction Transaction {get;set;}                                                         
UpdatedRowSource          Property   System.Data.UpdateRowSource UpdatedRowSource {get;set;}
 
Okay, so I guess we can call this one off. My co-worker just informed me that the previously working version of the script now no longer works. It is now throwing the exact same error message for the exact same function.

So I'm just going to chalk this one up to Microsoft breaking Powershell yet again. I should really just stop trying to use Powershell until it's out of beta.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
So I'm just going to chalk this one up to Microsoft breaking Powershell yet again. I should really just stop trying to use Powershell until it's out of beta.

No. I've done this very thing (albeit with MSSQL, not Access) and it worked fine.

You're not showing us your query. You're not learning how to debug properly. There's not much more we can do with our psychic debugging skills at this point.

I had a heck of a time getting Powershell to give me the output of $myobject.somevalue, rather than some kind of technical description of what $myobject was, which included an @ symbol.
This represents a fundamental misunderstanding of how powershell works at some point in your process. I'm not trying to be insulting. One of the big advantages of powershell is that you can just type out each line of your script at the command line one by one and retry until you get it right.

Read up on "powershell string interpolation". Try the following and see what you get for $query1

Code:
$foo = $myobject.SomeValue
$query1 = "select * from known_good_table where known_good_field = '$foo'"

Also, but are double quotes even legal for string constants in SQL? Maybe your query is
Code:
select * from known_good_table where known_good_field = "foo"
but your IDE is correcting it automatically to
Code:
select * from known_good_table where known_good_field = 'foo'

Finally, you should always be in the habit of parameterized queries and this wouldn't happen.

Something like:
Code:
$query1 = "SELECT * FROM known_good_table WHERE known_good_field = ?"
$cmd.CommandText = $query1
$cmd.Parameters.Add(new-object System.Data.OdbcParameter("p1", $myobject.SomeValue))
$reader = $cmd.ExecuteReader()

Your general frustration stems from the fact that you're scripting an SQL query using .NET libraries using powershell. That's 3 separate languages and you're not really expert in any of them to know where the line between them is happening.
 

Nazgutek

Ars Scholae Palatinae
1,298
[url=http:/civis/viewtopic.php?p=28660505#p28660505:3ncywmb0 said:
Archangel Mychael[/url]":3ncywmb0]
Code:
    $query1 = "select * from known_good_table where known_good_field = `"" + $myobject.SomeValue + "`""

I have no idea what on earth those double double-quotes are for, the above isn't even correct syntax.

Code:
    $query1 = "select * from known_good_table where known_good_field = `" + $myobject.SomeValue + "`"

But do what Pont posted and use parameterized queries.
 
Nazgutek, the extra double quotes are for adding quotes to the end query, so if $myobject.SomeValue is populated with the word Blah, then the query is

select * from sometable where somefield = "Blah"

The result of what you posted would be

select * from sometable where somefield = " + Blah +

And then Powershell actually wouldn't run it because the last `" aren't part of anything.



Pont, I did do the parameterization bit, but the error has not changed. When I write-host $query1 I get

select * from mytable where myfield = ?

I'm googling around to see other ways to do parameterization, because I'm pretty sure that's going to be the key to getting this to work. It's the mentality of, "That's the way it should be done, why should it work any other way?" So by trying to just make it simple just to get it working, and then make it better, I'm actually just making it harder. So I need to stop beating my head against that wall, because I don't think it's going to budge. If I just make it based on best practices from the get-go, maybe things will just fall into place.

One of the things I found when I was googling around was someone crating a SQL object specifically, rather than trying to just pass a string that happens to contain a valid SQL query through. I'll experiment with that as well and see what happens.
 
[url=http:/civis/viewtopic.php?p=28678233#p28678233:nc4umd8y said:
dragonlord[/url]":nc4umd8y]If you assign the query to a variable as a hard coded query does it work

e.g.
Code:
    $query1 = "select * from known_good_table where known_good_field = `known_good_value`"

Nope, I still get the ExecuteReader error. I tried this pretty early on, trying to "make it simple." But I think Powershell is expecting me to use best practices, and flat out won't work with simple. At least that's my current guess.

Edit:
Holy crap! Alright so this is going to be one of those things that feeds in to my frustrations with Powershell. And yes, this is a problem I run in to A LOT with Powershell. Let's relive the problem real quick.

I've been working up pretty high in the file trying to get this query to work against this table, using a where clause. It works when the where clause isn't there. I add the where clause, I get the error.

I was looking at the rest of the script, and down towards the bottom, I have a query that queries the exact same table, with a where clause on the exact same field. Or in other words, I have an example where what I am trying to do works, using the exact same commands. But when I do it in another place, it doesn't work. Boggle boggle!

Will post momentarily. Right now I'm just going to do some copy-pasta to see if I can get it working.
 
[url=http:/civis/viewtopic.php?p=28660505#p28660505:253wt6oo said:
Archangel Mychael[/url]":253wt6oo]
Code:
$conn = new-object data.odbc.odbcconnection
    $conn.ConnectionString = "dsn=$connectionname"
    $conn.open()
    
    $query1 = "select * from known_good_table where known_good_field = `"" + $myobject.SomeValue + "`""
    write-host $query1
    $cmd1 = $conn.CreateCommand()
    $cmd1.CommandText = $query1
    $data1 = $cmd1.ExecuteReader()
    $result1 = new-object "System.Data.DataTable"
    $result1.Load($data1)

^^ Broken. And now, working.

Code:
$cmd1 = $conn.CreateCommand()
    $cmd1.CommandText = "select * from known_good_table where known_good_field = '$myobject.SomeValue'"
    $data1 = $cmd1.ExecuteReader()
    $result1 = new-object "System.Data.DataTable"
    $result1.Load($data1)

Like Pont questioned. Are double quotes even legal? Well, in actual Access double quotes are required, and Access will actually break if given single quotes. However, I'm not working in Access, so it doesn't matter what Access wants (well, I imagine the query structure itself matters).

So, I still need to figure out how to do parameterization in Powershell. But I'll research that on my own and not subject you guys to my frustrations. If you've got any resources for me to go learn from, I'm game. Otherwise I'm just going to go read more in my Google search "Powershell parameterized query."

I'm sorry for subjecting you to my frustrations in the first place. Thank you everyone for stopping by and helping!


Edit:
[url=http:/civis/viewtopic.php?p=28678475#p28678475:253wt6oo said:
dragonlord[/url]":253wt6oo]Next trick, put the sql directly in the executeReader() function.

If that goes wrong you've probably forgotten to initialise the connection

Ha! Yeah no, that's one of the few times Powershell throws an error that makes sense. :)
 

Nazgutek

Ars Scholae Palatinae
1,298
[url=http:/civis/viewtopic.php?p=28678027#p28678027:l42wg60f said:
Archangel Mychael[/url]":l42wg60f]Nazgutek, the extra double quotes are for adding quotes to the end query, so if $myobject.SomeValue is populated with the word Blah, then the query is

select * from sometable where somefield = "Blah"

The result of what you posted would be

select * from sometable where somefield = " + Blah +

And then Powershell actually wouldn't run it because the last `" aren't part of anything.

No it wouldn't. At no point will what I suggested cause the + operators to appear in the resultant string. You've got your quotes all mixed up.

Try this:

Code:
$stuff = "Here's some ""quotes"" in a string"
write-host $stuff

which should print

Code:
Here's some "quotes" in a string

Note the single quote all alone, and the paired double double-quotes which lay inside paired double quotes.
 
[url=http:/civis/viewtopic.php?p=28674997#p28674997:3rt9mw55 said:
Pont[/url]":3rt9mw55]
Your general frustration stems from the fact that you're scripting an SQL query using .NET libraries using powershell. That's 3 separate languages and you're not really expert in any of them to know where the line between them is happening.

It's worse than that, it's also *ODBC*, which means there is ANOTHER layer of complexity. That's actually the one's that biting you. It's because you are using double quotes in what you are passing to ODBC. For reasons I do not understand, using double quotes instead of single quotes causes the error you are seeing. Run this:

Code:
select * from sometable where somefield='blah'
and you'll see that it works. This is NOT a powershell issue, it's an Access ODBC thing.
 
Status
Not open for further replies.