Hi all,

I have a program that need to insert the data to the database. In the form, I have 5 textbox control which required the user to insert the data in the database. To create this, I am using the visual studios 2005 and sql server 2005 for the database. I have post this part of the code, it works and has been inserted to the database but the problem is some of the other forums member said that the code can be implement in a better way. Could anyone help me?
Here is the part of the code where the user need to insert the data:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        Dim connectionString As String = "Data Source=ITCU-22\SQLEXPRESS;Initial Catalog=User;Integrated Security=SSPI;"

        Dim sql As String
        Dim conn As SqlConnection
        conn = New SqlConnection(connectionString)

        sql = "Insert Into receivedData (ReceivedName,TelephoneNo,TimeStamp,ReceivedMsg)values('" & (Trim(TextBox2.Text) & "','" & Trim(TextBox4.Text) & "','" & Trim(TextBox6.Text) & "','" & Trim(TextBox3.Text)) & "')"

        conn.Open()
        Dim cmd As New SqlCommand(sql, conn)
        cmd.ExecuteNonQuery()
        MsgBox("Message has been sent to the database")
        conn.Close()

Thanks

Regards
LiL_Is

u can make the connection object as module level variable.
moreover u dont need to create a string and then attach it to the connection object
for eg.

dim conn as new sqlconnection("Data Source=ITCU-22\SQLEXPRESS;Initial Catalog=User;Integrated Security=SSPI;")

similarly u can change the sql command as follows

dim cmd as new sqlcommand
cmd.commandtext="Insert Into receivedData (ReceivedName,TelephoneNo,TimeStamp,ReceivedMsg)values('" & (Trim(TextBox2.Text) & "','" & Trim(TextBox4.Text) & "','" & Trim(TextBox6.Text) & "','" & Trim(TextBox3.Text)) & "')"
cmd.connection=conn

hope this helps

Concatenating your query strings is poor coding. It is much better to use parameters. Take a look at sqlCommand.Parameters.AddWithValue. If you have any additional questions about it just let me know.

Another consideration is putting your query directly into a stored procedure in your database. Then you just have to link the command object to the stored procedure name and pass it the proper parameters.

commented: parameterized sql++; +17

i agree with tomw.
m sorry i forgot to add the parameter part mentioned by tomw.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.