Jump to content

Minimum Code For Database Work


justsomeguy
 Share

Recommended Posts

It's been a while since I've worked with C#, what's the minimum code necessary to retrieve a single value from get or post and insert it into a database table? Do I need to set up a whole .NET application and do any install on the server, or can I just write the code and copy a single file over like with ASP classic? Do I need more than one file?

Link to comment
Share on other sites

Something along these lines is the minimum amount of code you'll need.

// Hard code your connection string...string connectionString = "";// Or read it from a config file...//string connectionString = ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString;string commandText = "SELECT * FROM Table1 WHERE ID=@ID";using(SqlConnection connection = new SqlConnection(connectionString)){	SqlCommand command = new SqlCommand(commandText, connection);	command.CommandType = CommandType.Text;	command.Parameters.AddWithValue("@ID", Request.QueryString["MyGetParameter"]);	try	{		connection.Open();				SqlDataReader reader = command.ExecuteReader();		if(reader.Read())		{			// get at all your data here using reader["ColumnName"].		}	}	finally	{		command.Dispose();		connection.Close();	}}

If you set up a .NET web application, all you'd have to do is copy over the compiled DLL(s) when you make updates to the application.

Link to comment
Share on other sites

Cool, thanks for taking the time.
Pah, any time. It might also be a good idea to close and dispose the reader, I forgot to add that in there. Anything that's inside the "using" block will automatically be disposed, but it doesn't hurt to call it.
	try	{		connection.Open();				SqlDataReader reader = command.ExecuteReader();		if(reader.Read())		{			// get at all your data here using reader["ColumnName"].		}		reader.Close();		reader.Dispose();	}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...