views:

232

answers:

4

Here's my code

I seem to be getting an error SQL command cannot be converted to string with this code

Dim LogData2 As sterm.markdata = New sterm.markdata()

Dim query As New SqlCommand("Select * from openquery (db, 'SELECT * FROM table WHERE person=@person')")
query.Parameters.AddWithValue("@person", Session("number"))

Dim drCode2a As DataSet = LogData2.StermQ3(query)

dgBookings.DataSource = drCode2a.Tables(0).DefaultView
dgBookings.DataBind()

I tried adding in a Convert.ToString like this

Dim drCode2a As DataSet = LogData2.StermQ3(Convert.ToString(query))

And now I get this error

Could not find server 'System' in sysservers. Execute sp_addlinkedserver to add the server to sysservers

I'm obviously doing something wrong but not sure what - ASP.Net and SQL is all new to me so any help would be much appreciated.

Source code of StermQ3

StermQ3(String) As System.Data.DataSet

Public Function StermQ3(ByVal strSQL6 As String) As System.Data.DataSet

UPDATE

Source code as it is after some changes have been made

Sub Page_Load(ByVal Sender as Object, ByVal e as EventArgs)

Dim LogData2 As sterm.markdata = New sterm.markdata() 

Dim query As New SqlCommand("Select * from openquery (db, 'SELECT * FROM table WHERE person=@person')") 
query.Parameters.AddWithValue("@person", Session("number")) 
query.CommandType = CommandType.StoredProcedure
query.CommandText = "openquery"

Dim drCode2a As DataSet = LogData2.StermQ3(Convert.ToString(query)) 

dgBookings.DataSource = drCode2a.Tables(0).DefaultView 
dgBookings.DataBind()

End Sub

HTML is

<asp:DataGrid id="dgBookings" runat="server" AutoGenerateColumns="true" ShowHeader="true">

</asp:DataGrid>

Old way I used to do my query

Dim query As String = "Select * from openquery (db, 'SELECT * FROM table WHERE investor=''" + Session("number") + "'' ')"

That works if i replace my SQL Command but it is open to SQL Injection

UPDATE

I now have it so it work without the parameters bit here's my updated souce code any idea why it won't add the parameter value?

Dim conn As SqlConnection = New SqlConnection("server='server1'; user id='w'; password='w'; database='w'; pooling='false'")
   conn.Open()


Dim query As New SqlCommand("Select * from openquery (db, 'Select * from table where investor = @investor ') ", conn)
query.Parameters.AddWithValue("@investor", 69836)

dgBookings.DataSource = query.ExecuteReader
dgBookings.DataBind()

It works like this

Dim conn As SqlConnection = New SqlConnection("server='server1'; user id='w'; password='w'; database='w'; pooling='false'")
   conn.Open()


Dim query As New SqlCommand("Select * from openquery (db, 'Select * from table where investor = 69836') ", conn)

dgBookings.DataSource = query.ExecuteReader
dgBookings.DataBind()

Any ideas?

SOLUTION

Here's how i solved my issue

Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'")

conn.Open()

Dim query As New SqlCommand("DECLARE @investor varchar(10), @sql varchar(1000) Select @investor = 69836 select @sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + @investor + ''''''')' EXEC(@sql)", conn)

dgBookings.DataSource = query.ExecuteReader
dgBookings.DataBind()

Thanks for all the help

A: 

What LogData2.StermQ3 method does? My guess that it logs query your are going to execute. If it is so, than you should save your query in different variable and pass it to the method.

Andrew Bezzub
To be honest I have no idea what it does - i've taken over someone else's work so doing it as they did - how can i save my query in a different variable and pass it? Thanks
Jamie Taylor
I think the best way to make something working right is to understand what it is doing. So you should try to find out...
Andrew Bezzub
+3  A: 

Have you debugged to find out what StermQ3 does? You are passing the string reference from an SqlCommand-Object to it what might be nonsense. I think you need its CommandText Property, but you have a problem because you don't get the actually SQL Text what is executed on the database. The parameters are evaluated in the Database and not here.

What you can try is following:

 Dim commandText As String = query.CommandText
 For Each parameter As System.Data.SqlClient.SqlParameter In query.Parameters
     commandText=commandText.Replace(parameter.ParameterName, parameter.Value.ToString)
 Next
 Dim drCode2a As DataSet = LogData2.StermQ3(commandText)

But i don't think that you want that, because you are again open for SQL-Injection(StermQ3 returns a Dataset). I think StermQ3 needs to get an overloaded version that takes a SQLCommand as parameter.

EDIT: I think the SqlCommand does not know that it should execute a StoredProcedure. Set its CommandType and as CommandText the name of the SP:

query.CommandType = CommandType.StoredProcedure
query.CommandText = "openquery"
Tim Schmelter
I don't actually know how to debug it - i literally know nothing about ASP.Net i've done some queries and that's about it i've been thrown in the deep end with this stuff after a guy recently left
Jamie Taylor
Set a breakpoint in Visual Studio by clicking leftmost in the source-code window at the line you want to stop(Dim drCode2a As DataSet = LogData2.StermQ3(query)). Then start the application and wait till it stops there. Now you can check variables etc. by hovering them, open the quick watch window(right-click on a variable) or add watches to see directly when the values are changing.http://odetocode.com/Articles/425.aspx
Tim Schmelter
I don't seem to have Visual Studio on my PC i'm guessing this is a necessity if i'm going to be able to debug?
Jamie Taylor
What IDE do you have? VS 2010 Express is for free: http://www.microsoft.com/express/downloads/
Tim Schmelter
All I know is that I do everything in Dreamweaver no other program
Jamie Taylor
http://stackoverflow.com/questions/783532/where-to-start-with-asp-net-in-c-and-dreamweaver
Tim Schmelter
I see installing VS2010 Express right now Thanks
Jamie Taylor
@Tim thanks for the help so far I'm all set up on VS now and i've set the breakpoint when I hover over the bit that you mentioned `query = {System.Data.SqlClient.SqlCommand}` which is obviously why i'm getting the error. I'm not really sure what it means though? I know i need to somehow convert it into a string and pass it
Jamie Taylor
@ Jamie Taylor: step into the StermQ3-Function to see what causes the exception. As i mentioned before, overload that function with one that takes a SqlCommand as parameter and all should work.I guess that StermQ3 is creating a SQlCommand itself, that is not needed anymore when it is passed per parameter.
Tim Schmelter
I had a look at StermQ3 definition and it looks like this `StermQ3(String) As System.Data.DataSet`
Jamie Taylor
Yes, naturally. Add a StermQ3 function to this class which takes a SqlCommand as Parameter and copy/paste all but the creation of the SqlCommand of the old one into this new function. Then call the new function from the old. Please edit your question and add the sourcecode from the StermQ3 into it.
Tim Schmelter
How do I add a StermQ3 function to that class which takes a SqlCommand as Parameter?
Jamie Taylor
Show us the function and we show you how you could do that ;-)
Tim Schmelter
Do I need to post more source code? Everything in my question is pretty much what I need to do?
Jamie Taylor
Where is the StermQ3 Funtion(of Class markdata) in your question? There is only the call of that function!
Tim Schmelter
Updated question with what I think you need? Sorry i'm not good with this
Jamie Taylor
No problem. But you have only posted the signature of the function and not the function itself. Is it in another DLL you don't have the sourcecode from?
Tim Schmelter
StermQ3 seems to the only DLL file it accesses?
Jamie Taylor
Can you step into(F11) StermQ3 while debugging? http://odetocode.com/Articles/425.aspxSet a breakpoint at the line `Dim drCode2a As DataSet = LogData2.StermQ3(query)` and hit F11 to go into the function. Then copy/paste it.
Tim Schmelter
A: 

It looks that the function takes a query, not SQL command. Try the following:

Dim query As String = "Select * from openquery (db, 'SELECT * FROM table WHERE person=" & Session("number") & "')"
Dim drCode2a As DataSet = LogData2.StermQ3(query)

dgBookings.DataSource = drCode2a.Tables(0).DefaultView
dgBookings.DataBind()

Yes, it may not prevent you from SQL injections, so the best you can do in this case is to use

query = query.Replace("'", "''")

before you pass it to that function. In all other cases use parametrized queries.

negative
By doing this it gives me a syntax error - its converting the `'` before `SELECT` to a `''` and erroring
Jamie Taylor
Completely forgot about that, just ignore the last part of my answer then =) Otherwise rewrite StermQ3 function and make it take sqlcommand instead of string.
negative