How to connect to a SQL database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dougancil
    Contributor
    • Apr 2010
    • 347

    How to connect to a SQL database

    I have the following code:

    Code:
    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>
        <style type="text/css">
            #Submit1
            {
                width: 131px;
            }
            .style1
            {
                color: #FF0000;
            }
        </style>
    <script language="javascript" type="text/javascript">
    // <!CDATA[
    
    function Submit1_onclick() {
      Dim connectionString As String
            Dim cnn As SqlConnection
            Dim myCommand As SqlCommand
            Dim dteReturnValue As DateTime = Nothing
            'the connection string to the SQL server'
            connectionString = "Data Source=10.2.1.41;Initial Catalog=MDR;uid=xxxxx;password=xxxxxxx"
            cnn = New SqlConnection(connectionString)
            cnn.Open()
     
       myCommand.CommandText = "insert into Exceptions2 values('" & exceptiondateInput.Text & "','" & starttimeInput.Text & "','" & txtAddress.Text & "','" & endtimeInput.Text & "','" & duration.text & "')"
       myCommand.Connection = con
     
       con.Open()
       myCommand.ExecuteNonQuery()
       con.Close() 
    }
    
    // ]]>
    </script>
    </head>
    <body>
    <br />
        <form id="form1" runat="server">
        <div align="left">
        
            <asp:DropDownList ID="OperatorDropdown" runat="server" 
                DataSourceID="SqlDataSource1" DataTextField="employeenumber" 
                DataValueField="employeenumber" Height="23px" Width="130px">
            </asp:DropDownList>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:MDRConnectionString %>" 
                SelectCommand="SELECT [employeenumber] FROM [Employees]">
            </asp:SqlDataSource>
    &nbsp;&nbsp; Choose an Operator
            <br />
            <br />
            <br />
            <asp:TextBox ID="exceptiondateInput" runat="server" Width="130px" Height="23px"></asp:TextBox>
            &nbsp; <span class="style1">*</span> Exception Date &nbsp;<asp:RegularExpressionValidator 
                ID="DateValidator" runat="server" 
                ControlToValidate="exceptiondateInput"
                ValidationExpression="^\d{1,2}\/\d{1,2}\/\d{4}$" 
                ErrorMessage="Please Enter the Date Correctly"></asp:RegularExpressionValidator>
            <br />
            <br />
            <br />
            <asp:TextBox ID="starttimeInput" runat="server" Width="130px" Height="23px"></asp:TextBox>
            &nbsp; <span class="style1">*</span> Start Time &nbsp;<asp:RegularExpressionValidator
                ValidationExpression="^([0-1][0-9]|[2][0-3]):([0-5][0-9])$"
                ID="StartTimeValidator" runat="server" 
                ErrorMessage="You Must Supply an Start Time" 
                ControlToValidate="starttimeInput"></asp:RegularExpressionValidator><br />
            <br />
            <br />
            <asp:TextBox ID="endtimeInput" runat="server" Width="130px" Height="23px"></asp:TextBox>
            &nbsp; <span class="style1">*</span> End Time &nbsp;<asp:RegularExpressionValidator 
                ID="EndTimeValidator" runat="server" 
                ValidationExpression="^([0-1][0-9]|[2][0-3]):([0-5][0-9])$"
                ErrorMessage="You Must Supply an End Time" 
                ControlToValidate="endtimeInput"></asp:RegularExpressionValidator>
            <br />
            <br />
            <br />
            <asp:TextBox ID="durationInput" runat="server" Width="130px" Height="23px"></asp:TextBox>
    &nbsp; <span class="style1">*</span> Duration &nbsp;<asp:RequiredFieldValidator 
                ID="DurationValidator" runat="server" 
                ErrorMessage="Exception Duration Must Be Entered" 
                ControlToValidate="durationInput"></asp:RequiredFieldValidator>
            <br />
            <br />
            <br />
            <asp:DropDownList ID="Reason" runat="server" Height="23px" Width="206px">
                <asp:ListItem Value="NoSelection">--- No Selection --</asp:ListItem>
                <asp:ListItem>1. Approved Technical Reason</asp:ListItem>
                <asp:ListItem>2. Coaching Session</asp:ListItem>
                <asp:ListItem>3. ETO</asp:ListItem>
                <asp:ListItem>4. Sick Leave</asp:ListItem>
                <asp:ListItem>5. Special Project</asp:ListItem>
                <asp:ListItem>6. Supervisor Meeting</asp:ListItem>
                <asp:ListItem>7. Vacation</asp:ListItem>
            </asp:DropDownList>
        
        &nbsp;Choose a reason for exception  &nbsp;<asp:compareValidator id="reasonValidator" 
                runat="server" ControlToValidate="Reason" 
                ValueToCompare="NoSelection" Operator="NotEqual"
                ErrorMessage="Please Select an item" />
            <br />
            <br />
            <br />
            <asp:DropDownList ID="Approved" runat="server" Width="130px" Height="23px">
            <asp:ListItem Value="NoSelection">--- No Selection --</asp:ListItem>
            <asp:ListItem>Patrice Paul</asp:ListItem>
            <asp:ListItem>Zach Cochran</asp:ListItem>
            </asp:DropDownList>
    &nbsp;Approved By &nbsp;<asp:compareValidator id="CompareValidator1" 
                runat="server" ControlToValidate="Approved" 
                ValueToCompare="NoSelection" Operator="NotEqual"
                ErrorMessage="Please Select an item" />
            <br />
            <br />
            <br />
            <input id="Submit1" type="submit" value="Submit" onclick="return Submit1_onclick()" /><br />
            <br />
            <br />
            <span class="style1">* all fields with asterisks must be filled out</span><br />
            </div>
        </form>
    </body>
    </html>
    and I'm trying to use that to submit to my database, but when I click on the submit button, no data is being inserted into my database, but I'm also not receiving any errors. Can someone maybe point out why?

    Thank you

    Doug
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    You should not be creating your SQL command by concatenating user input directly into it. This leaves you wide open to a SQL Injection attack (where the user inputs SQL instead of the intended value and because you are adding it into your SQL command, their SQL command gets executed). You should be using Parameters to avoid this type of attack.

    Please review: How to use a database in your program.

    After modifying your code to use parameters, see if it works. You can check the number of rows that were effected by the update by checking the Integer that is returned by the ExecuteNonQuery () method.

    -Frinny
    Last edited by Frinavale; Oct 7 '10, 01:16 PM.

    Comment

    • dougancil
      Contributor
      • Apr 2010
      • 347

      #3
      Frinny,

      If the best way would be to use Parameters to input data directly into my SQL with the drop down lists and text boxes I have, since I'm taking values from the users, what would be the best way to accept input from the users?

      Doug

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        You accept the input from the users using TextBoxes and DropDownLists and any other types of controls you need to do the task.

        Then you validate that the input they provided is correct according to your requirements.

        Then you supply the values the input to the SqlCommand using it's Parameters Property so that the user input can be used to query or update your database.

        When you use parameters, any user provided input will be treated as a "Literal" instead of as part of the command. It is not compiled into the SQL query/update that you are going to execute.

        Does this make sense?

        Comment

        • dougancil
          Contributor
          • Apr 2010
          • 347

          #5
          Frinny,

          Ok so then because I'm using regular expression validation for most of the text boxes, what you're telling me then is that by using parameters, that instead of doing my validation via expression validation, that I'm shifting away from client validation to server side validation correct? Also if that's the case, can you give me an example of how to capture a text box's input in a sqlcom.paramete rs.add statement?

          Thank you,

          Doug

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            Nope,

            I'm telling you to leave all of your validation in.
            Do validation client-side and server side...but still participate in good database input-sanitation practices by using parameters.

            You should have several layers of data validation and when it comes to entering data into a database you should still use parameters.

            -Frinny
            Last edited by Frinavale; Oct 7 '10, 03:51 PM.

            Comment

            • dougancil
              Contributor
              • Apr 2010
              • 347

              #7
              Ok so since I've never worked with parameters before, can you give me an example so I won't have to come back later and ask.

              Thank you

              Doug

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                Follow either the SqlCommand.Para meters Property link I posted or the How to use a database in your program link I posted...

                They both have examples on how to use parameters.

                -Frinny

                Comment

                • dougancil
                  Contributor
                  • Apr 2010
                  • 347

                  #9
                  Frinny,

                  What I don't know is how to pass the parameters from a text box to the add.parameters. That's my question.

                  I can understand the structure but don't understand where the textbox or dropdown values would be in the statements.

                  Comment

                  • Frinavale
                    Recognized Expert Expert
                    • Oct 2006
                    • 9749

                    #10
                    I see.

                    Like this:
                    Code:
                        Dim connectionString As String = "Data Source=10.2.1.41;Initial Catalog=MDR;uid=xxxxx;password=xxxxxxx"
                       
                        Dim commandText As String = _
                            "insert into Exceptions2 " & _
                            "values(@exceptiondate, @starttime, @address, @endtime, @duration)"
                    
                    
                        Using connection As New SqlConnection(connectionString)
                            Dim command As New SqlCommand(commandText, connection)
                            command.Parameters.Add("@exceptiondate", SqlDbType.VarChar)
                            command.Parameters("@exceptiondate").Value = exceptiondateInput.Text
                    
                            command.Parameters.Add("@starttime", SqlDbType.VarChar)
                            command.Parameters("@starttime").Value = starttimeInput.Text
                    
                            command.Parameters.Add("@address", SqlDbType.VarChar)
                            command.Parameters("@address").Value = txtAddress.Text
                    
                            command.Parameters.Add("@endtime", SqlDbType.VarChar)
                            command.Parameters("@endtime").Value = endtimeInput.Text
                    
                    
                            command.Parameters.Add("@duration", SqlDbType.VarChar)
                            command.Parameters("@duration").Value = duration.Text
                    
                            Try
                                connection.Open()
                                Dim rowsAffected As Integer = command.ExecuteNonQuery()
                              
                            Catch ex As Exception
                                myErrorMessageLabel.Text = ex.Message
                            End Try
                        End Using
                    -Frinny

                    Comment

                    • dougancil
                      Contributor
                      • Apr 2010
                      • 347

                      #11
                      Frinny thanks. That helps a lot. One last question, what's the best way to pass my dropdown list variables to the sql server? This one is databound

                      Code:
                      <asp:DropDownList ID="OperatorDropdown" runat="server" 
                                  DataSourceID="SqlDataSource1" DataTextField="employeenumber" 
                                  DataValueField="employeenumber" Height="23px" Width="130px">
                              </asp:DropDownList>
                              <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                                  ConnectionString="<%$ ConnectionStrings:MDRConnectionString %>" 
                                  SelectCommand="SELECT [employeenumber] FROM [Employees]">
                              </asp:SqlDataSource>
                      While the other two are not.

                      Comment

                      • Frinavale
                        Recognized Expert Expert
                        • Oct 2006
                        • 9749

                        #12
                        I haven't worked with bound DropDownLists in the past but I would think that you could just access the OperatorDropdow n.SelectedItem. Value property and set the parameter's value to it... like I did above.

                        Comment

                        • dougancil
                          Contributor
                          • Apr 2010
                          • 347

                          #13
                          so like this for the databound dropdown?

                          Code:
                          command.Parameters.Add("@employeenumber", SqlDbType.Varchar)
                                  command.Parameters("@employeenumber".value = OperatorDropdown.SelectedItem.Value
                          and like this for the non-databound?

                          Code:
                          command.Parameters.Add("@code", SqlDbType.Varchar)
                                  command.Parameters("@code").Value = listitem.value

                          Comment

                          • Frinavale
                            Recognized Expert Expert
                            • Oct 2006
                            • 9749

                            #14
                            You're missing a")" in your code. It should be....
                            Code:
                            command.Parameters.Add("@employeenumber", SqlDbType.Varchar)
                            command.Parameters("@employeenumber").value = OperatorDropdown.SelectedItem.Value
                            When you bind your DropDownList you set the DataTextField and the DataValueField properties. These are not necessarily the same thing (in your case they are set to the same thing). You would need to choose the correct "SelectedIt em" property accordingly. In your case either OperatorDropdow n.SelectedItem. Value or OperatorDropdow n.SelectedItem. Text will work.

                            Comment

                            • dougancil
                              Contributor
                              • Apr 2010
                              • 347

                              #15
                              Frinny,

                              What about for the non-bound dropdown? Is that correct? Oh and thank you for pointing out the missing ")". I corrected that.

                              Comment

                              Working...