Tuesday, March 13, 2012

simple function question

hey everyone, i am a newbie to asp.net, I am a classic asp coder and working with databases is a little different.

in asp i have a function called

getProductName(Productid)

basically all i do is pass the productid to it and in the function is opens the database runs a query and returns the product name.

Can someone just point me in the right direction to recreate this in asp.net using vb.net code

Much help is appreciated

Hello Themaze,

This little function could retrieve the value you want:

private Function GetProduct(byval Productid as integer)

dim ProductName as string
dim myConnection as new Sqlconnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;")

Dim myCommand As New SqlCommand("Select Productname from Products where ProductId=" & productid,myConnection)
Myconnection.open()
ProducttName = myCommand.executescalar()
Myconnection.close()
end function

The function Exceutescalar retrieve only the first row of the first column returned by your query... If you only need the productname this is the fastest way to get it.

Hope this will help you.

Leketje


Here's how your function should look.

Public Function GetProductName(ByVal productIDAs Integer)As String
Dim m_ProductNameAs String
Dim m_SqlConnectionAs System.Data.SqlClient.SqlConnection

Try
Dim m_SqlQuery_SelectAs String
m_SqlQuery_Select ="SELECT Something FROM SomeTable WHERE ProductID = '" & productID &"';"

m_SqlConnection =New System.Data.SqlClient.SqlConnection("server=;user id=;password=;database=;")

Dim m_SqlCommand As New System.Data.SqlClient.SqlCommand(m_SqlQuery_Select, m_SqlConnection)

m_SqlConnection.Open()
m_ProductName = m_SqlCommand.ExecuteScalar()
Finally
If Not m_SqlConnectionIs Nothing Then
If m_SqlConnection.ConnectionState = ConnectionState.OpenThen
m_SqlConnection.Close()
End If
End If
End Try

Return m_ProductName
End Function


just a small note on the code !!

it is better to use parameters and or stored procedure and not to use the sle statemnt itslef alone to prevent sql injections


Hello Ryan:

Using Parameters is a MUSTBig Smile [:D]

Working without parameters cause SQL Injection and that is bad for your application.

Regards


Yup. In my actual web applications, I use nothing but stored procedures, but for the simplicity of this example, SQL in the code works fine.

Good !!

i only wanted to ensure the methodlogy is correct not only the code !!

all the best !!

0 comments:

Post a Comment