Tuesday, March 27, 2012

Connecting to SQL server

Hi

i'm having lots of problems connecting my application to a database. I'm using Visual Web developer 2008 (coding in VB) and trying to connect to a locally installed version SQL server Express.

what i'm trying to do is using a DropDownList box get a user to select a name. This will then automaticly run a SQL query to pull data out of the DB and into a GridView. i'm coding (in VB only) everything under the DropDownList.SelectedIndexChanged section.


the query i want to run is -

SELECT name, description, data_added, priority_id FROM task WHERE (owner_id = (SELECT owner_id FROM owner WHERE (owner_id = @.owner_id)

The owner_id field references another table (owner). Therefore i run the inner query to get the owner_id based on the selected name in the dropDownlist, then let the outer query pull out all tasks which match the result from the inner query.

my code at the moment is

Dim dsAsNew DataSet

Dim myconnectionAs SqlConnection'create a connection

'create connection to DB

myconnection.ConnectionString ="server=localhost;database=taskDB"

'create the sql command

Dim objcmdAsNew SqlCommand("SELECT name, description, data_added, priority_id FROM task WHERE (owner_id = (SELECT owner_id FROM owner WHERE (owner_id = @.owner_id)))", myconnection)

objcmd.Connection.Open()

'open the connection to DB

Dim objreaderAs SqlDataReader = objcmd.ExecuteReader

Dim daAsNew SqlDataAdapter

da.SelectCommand = objcmd

'fails here sql not allowing remote connection

da.Fill(ds)

Me.GridView1.DataSource = da

Me.GridView1.DataBind()

'close the connection to the DB

objcmd.Connection.Close()

The application fails when you select a name from the drop down box.

fails at - myconnection.ConnectionString ="server=localhost;database=taskDB"Error is "Object reference not set to an instance of an object." If i comment out this line, i get the same error but at it stopps at the objcmd.connection.open(). Strange.

Can anyone tell me what i am doing wrong? Have i setup the connection to the DB ok?

Thanks

Cj

You to use the keyword New when creating an object of class SqlConnection.

Dim myconnectionAs New SqlConnection

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

Also, the connection string to the database doesn't seem to be right. Have a look at this and try modifying your connection string:

http://www.connectionstrings.com/?carrier=sqlserver2005

No comments:

Post a Comment