Monday, March 12, 2012

programmaticaly connecting and accessing a database

I have not been able to find a code example anywhere. Someone please post the code to do this. I would be forever grateful.

I would like the code to be in C#. I want to connect to a database and then select all from a table.

thanks

Forever is a very long time my new friend.

(you need to list all the fields yourself. in my example, I just have one field. You can also leave out the WHERE clause and you will get all records).

try
{
SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["CodeCampSV06"].ConnectionString);
sqlConnection.Open();

string sqlSelect = "select VistaSlotsId FROM attendees WHERE Username = @.Username";
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
sqlCommand.Parameters.Add("@.Username", SqlDbType.VarChar).Value = username;
vistaIdStatus = (int)sqlCommand.ExecuteScalar();

sqlConnection.Close();
sqlConnection.Dispose();

}
catch (Exception ee)
{
throw new ApplicationException(ee.ToString());
}

|||Does this code work with asp.net 2.0? sorry i forgot to mention that.|||yes it works with asp.net 2.0. That is what I am using|||

ok thanks for all the help. However i am having trouble trying to figure out what "CodeCampSV06" is. Is it the name of the DB? if so, it is not working for me.

thanks

|||

Its the name of the connectionString in the application's web.config file.

bullpit

|||

Have a look at this:

http://msdn2.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx

good luck...

bullpit

|||

I have now used the correct string for webconfig.

But Now i keep getting this error

Error 2 The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?) C:\mine\MyProjects\Work4Tips\insert.aspx 19 9 C:\...\Work4Tips\
c

how do I solve this? The page i am trying to get this to run in is using masterpages. I am placing the code between the server tags and in these tags between a clickon method. Do I have to use a directive, if so what is it?

thanks for all your help... I am just so lost right now.

|||

Add this to your using directives list at the top of your aspx.cs file:

using

System.Data.SqlClient;

using

System.Data;

bullpit

|||

what if I am using inline code and not code behind?

does not work anywhere I place it.

|||

You can use this with your page directives at the top of the aspx page.

<%@. Import Namespace="System.Data" %>

bullpit

|||

You can also use a fully qualified statement like this:

System.Data.SqlClient.SqlConnection =new System.Data.SqlClient.SqlConnection(...)

bullpit|||

Correction to last post:

System.Data.SqlClient.SqlConnection sqlConnection =new System.Data.SqlClient.SqlConnection

No comments:

Post a Comment