Monday, March 26, 2012

Multiple Inserts

Hi, I'm trying to create a form where new names can be added to a database. The webform looks like this:
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
Name:<asp:TextBox ID="newName" runat="server" />
<INPUT id="NewUserBtn" type="button" value="Create New User" name="NewUserBtn" runat="server"
onServerClick="NewBtn_Click">
</form>
And the code behind looks like this:
Public Sub NewBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewUserBtn.ServerClick
Dim DS As DataSet
Dim MyConnection As SqlConnection
Dim MyCommand As SqlDataAdapter

MyConnection = New SqlConnection("server=databaseserver;database=db;uid=uid;pwd=pwd")
MyCommand = New SqlDataAdapter("insert into certifications (name) values ('" & newName.Text & "'); select * from certifications", MyConnection)

DS = New DataSet
MyCommand.Fill(DS, "Titles")

Response.Redirect("WebForm1.aspx", True)
End Sub
When I try to insert one name it works. When I try to insert a second name, it overwrites the old one. Why is that?
Thanks.
James

(1) Always MASK your connection string when posting on public forums like these. DO NOT post your userid/pwd.
(2) You could do this in a better way by using a stored proc with @.name as an input parameter.
CREATE PROC usp_InsertName ( @.name VARCHAR(100) )
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Certifications
VALUES (@.name)
SELECT
<col1>, <col2>...
FROM
Cerfications
SET NOCOUNT OFF
END

(3) Its a bad programming practice to say "SELECT * FROM..". Always explicitly write out your column names.
(4) Currently you are hardcoding the variable names. Your SQL Server is susceptible for SQL Injection Attacks (google for more info). You should use Parameterized queries to prevent this.|||Thanks for the tips. I'll take care of the select statement and look into using parameterized queries. My problem is that when I run the insert statement, it overwrites the values in there with just the information that is being submitted instead of creating a new row. What I would like is to be able to load the page with any number of entries and just enter a new row and not enter them all at once. Thanks.
James|||If you use the stored proc like I posted above it would work.

No comments:

Post a Comment