Best Practice for Inserting Data into SQL in 2.0

H

hooterbite

I have a simple form. I would like to insert the values from the form
into a SQL table. What is the best way to do it?
I assume that using a stored procedure is preferable to using the
UpdateCommand="Insert into..."
When using a stored procedure, is it better to use a SqlDataSource or
an ObjectDataSource? Is it better to make it formview and use
asp:parameter or not put it in a formview and use asp:FormParameter, or
is there a better way?
 
M

Michael Kolias

I think the best way is to use a stored procedure with an SqlCommand object.
It's faster and safer.
Suppose your stored proc looks like this:

CREATE PROC [your_procedure_name]
@Param1 datatype,
@Param2 datatype,
@Param3 datatype,
@Param4 datatype
AS
INSERT INTO table_name (field1, field2, field3, field4) VALUES (@Param1,
@Param2, @Param3, @Param4)
GO

Then your code should look like this:

SqlConnection oCn = new SqlConnection(yourconnectionstring);
oCn.Open();
SqlCommand oCmd = oCn.CreateCommand();

oCmd.Parameters.Add("@Param1", SqlDbType.datatype, size).Value =
"param1_value"'
oCmd.Parameters.Add("@Param2", SqlDbType.datatype, size).Value =
"param2_value"'
oCmd.Parameters.Add("@Param3", SqlDbType.datatype, size).Value =
"param3_value"'
oCmd.Parameters.Add("@Param4", SqlDbType.datatype, size).Value =
"param4_value"'

oCmd.ExecuteNonQuery();
oCn.Close()

oCn.Dispose();
oCmd.Dispose();

I also suggest to you used try...catch...finally statements.
 
H

hooterbite

Michael -
Thanks for your response. Do you use .NET 2.0? If so, any thoughts on
my questions?

Is it better to use a SqlDataSource or an ObjectDataSource?

Is it better to make it formview and use asp:parameter or not put it
in a formview and use asp:FormParameter?

Is there a better way?

I know how to use stored procedures. The question is where should the
SP be - and what is the best way to call it?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top