473,385 Members | 1,620 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

How to connect to a SQL database

347 100+
I have the following code:

Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head runat="server">
  7.     <title>Untitled Page</title>
  8.     <style type="text/css">
  9.         #Submit1
  10.         {
  11.             width: 131px;
  12.         }
  13.         .style1
  14.         {
  15.             color: #FF0000;
  16.         }
  17.     </style>
  18. <script language="javascript" type="text/javascript">
  19. // <!CDATA[
  20.  
  21. function Submit1_onclick() {
  22.   Dim connectionString As String
  23.         Dim cnn As SqlConnection
  24.         Dim myCommand As SqlCommand
  25.         Dim dteReturnValue As DateTime = Nothing
  26.         'the connection string to the SQL server'
  27.         connectionString = "Data Source=10.2.1.41;Initial Catalog=MDR;uid=xxxxx;password=xxxxxxx"
  28.         cnn = New SqlConnection(connectionString)
  29.         cnn.Open()
  30.  
  31.    myCommand.CommandText = "insert into Exceptions2 values('" & exceptiondateInput.Text & "','" & starttimeInput.Text & "','" & txtAddress.Text & "','" & endtimeInput.Text & "','" & duration.text & "')"
  32.    myCommand.Connection = con
  33.  
  34.    con.Open()
  35.    myCommand.ExecuteNonQuery()
  36.    con.Close() 
  37. }
  38.  
  39. // ]]>
  40. </script>
  41. </head>
  42. <body>
  43. <br />
  44.     <form id="form1" runat="server">
  45.     <div align="left">
  46.  
  47.         <asp:DropDownList ID="OperatorDropdown" runat="server" 
  48.             DataSourceID="SqlDataSource1" DataTextField="employeenumber" 
  49.             DataValueField="employeenumber" Height="23px" Width="130px">
  50.         </asp:DropDownList>
  51.         <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  52.             ConnectionString="<%$ ConnectionStrings:MDRConnectionString %>" 
  53.             SelectCommand="SELECT [employeenumber] FROM [Employees]">
  54.         </asp:SqlDataSource>
  55. &nbsp;&nbsp; Choose an Operator
  56.         <br />
  57.         <br />
  58.         <br />
  59.         <asp:TextBox ID="exceptiondateInput" runat="server" Width="130px" Height="23px"></asp:TextBox>
  60.         &nbsp; <span class="style1">*</span> Exception Date &nbsp;<asp:RegularExpressionValidator 
  61.             ID="DateValidator" runat="server" 
  62.             ControlToValidate="exceptiondateInput"
  63.             ValidationExpression="^\d{1,2}\/\d{1,2}\/\d{4}$" 
  64.             ErrorMessage="Please Enter the Date Correctly"></asp:RegularExpressionValidator>
  65.         <br />
  66.         <br />
  67.         <br />
  68.         <asp:TextBox ID="starttimeInput" runat="server" Width="130px" Height="23px"></asp:TextBox>
  69.         &nbsp; <span class="style1">*</span> Start Time &nbsp;<asp:RegularExpressionValidator
  70.             ValidationExpression="^([0-1][0-9]|[2][0-3]):([0-5][0-9])$"
  71.             ID="StartTimeValidator" runat="server" 
  72.             ErrorMessage="You Must Supply an Start Time" 
  73.             ControlToValidate="starttimeInput"></asp:RegularExpressionValidator><br />
  74.         <br />
  75.         <br />
  76.         <asp:TextBox ID="endtimeInput" runat="server" Width="130px" Height="23px"></asp:TextBox>
  77.         &nbsp; <span class="style1">*</span> End Time &nbsp;<asp:RegularExpressionValidator 
  78.             ID="EndTimeValidator" runat="server" 
  79.             ValidationExpression="^([0-1][0-9]|[2][0-3]):([0-5][0-9])$"
  80.             ErrorMessage="You Must Supply an End Time" 
  81.             ControlToValidate="endtimeInput"></asp:RegularExpressionValidator>
  82.         <br />
  83.         <br />
  84.         <br />
  85.         <asp:TextBox ID="durationInput" runat="server" Width="130px" Height="23px"></asp:TextBox>
  86. &nbsp; <span class="style1">*</span> Duration &nbsp;<asp:RequiredFieldValidator 
  87.             ID="DurationValidator" runat="server" 
  88.             ErrorMessage="Exception Duration Must Be Entered" 
  89.             ControlToValidate="durationInput"></asp:RequiredFieldValidator>
  90.         <br />
  91.         <br />
  92.         <br />
  93.         <asp:DropDownList ID="Reason" runat="server" Height="23px" Width="206px">
  94.             <asp:ListItem Value="NoSelection">--- No Selection --</asp:ListItem>
  95.             <asp:ListItem>1. Approved Technical Reason</asp:ListItem>
  96.             <asp:ListItem>2. Coaching Session</asp:ListItem>
  97.             <asp:ListItem>3. ETO</asp:ListItem>
  98.             <asp:ListItem>4. Sick Leave</asp:ListItem>
  99.             <asp:ListItem>5. Special Project</asp:ListItem>
  100.             <asp:ListItem>6. Supervisor Meeting</asp:ListItem>
  101.             <asp:ListItem>7. Vacation</asp:ListItem>
  102.         </asp:DropDownList>
  103.  
  104.     &nbsp;Choose a reason for exception  &nbsp;<asp:compareValidator id="reasonValidator" 
  105.             runat="server" ControlToValidate="Reason" 
  106.             ValueToCompare="NoSelection" Operator="NotEqual"
  107.             ErrorMessage="Please Select an item" />
  108.         <br />
  109.         <br />
  110.         <br />
  111.         <asp:DropDownList ID="Approved" runat="server" Width="130px" Height="23px">
  112.         <asp:ListItem Value="NoSelection">--- No Selection --</asp:ListItem>
  113.         <asp:ListItem>Patrice Paul</asp:ListItem>
  114.         <asp:ListItem>Zach Cochran</asp:ListItem>
  115.         </asp:DropDownList>
  116. &nbsp;Approved By &nbsp;<asp:compareValidator id="CompareValidator1" 
  117.             runat="server" ControlToValidate="Approved" 
  118.             ValueToCompare="NoSelection" Operator="NotEqual"
  119.             ErrorMessage="Please Select an item" />
  120.         <br />
  121.         <br />
  122.         <br />
  123.         <input id="Submit1" type="submit" value="Submit" onclick="return Submit1_onclick()" /><br />
  124.         <br />
  125.         <br />
  126.         <span class="style1">* all fields with asterisks must be filled out</span><br />
  127.         </div>
  128.     </form>
  129. </body>
  130. </html>
  131.  
  132.  
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
Oct 6 '10 #1
20 1986
Frinavale
9,735 Expert Mod 8TB
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
Oct 7 '10 #2
dougancil
347 100+
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
Oct 7 '10 #3
Frinavale
9,735 Expert Mod 8TB
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?
Oct 7 '10 #4
dougancil
347 100+
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.parameters.add statement?

Thank you,

Doug
Oct 7 '10 #5
Frinavale
9,735 Expert Mod 8TB
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
Oct 7 '10 #6
dougancil
347 100+
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
Oct 7 '10 #7
Frinavale
9,735 Expert Mod 8TB
Follow either the SqlCommand.Parameters 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
Oct 7 '10 #8
dougancil
347 100+
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.
Oct 7 '10 #9
Frinavale
9,735 Expert Mod 8TB
I see.

Like this:
Expand|Select|Wrap|Line Numbers
  1.     Dim connectionString As String = "Data Source=10.2.1.41;Initial Catalog=MDR;uid=xxxxx;password=xxxxxxx"
  2.  
  3.     Dim commandText As String = _
  4.         "insert into Exceptions2 " & _
  5.         "values(@exceptiondate, @starttime, @address, @endtime, @duration)"
  6.  
  7.  
  8.     Using connection As New SqlConnection(connectionString)
  9.         Dim command As New SqlCommand(commandText, connection)
  10.         command.Parameters.Add("@exceptiondate", SqlDbType.VarChar)
  11.         command.Parameters("@exceptiondate").Value = exceptiondateInput.Text
  12.  
  13.         command.Parameters.Add("@starttime", SqlDbType.VarChar)
  14.         command.Parameters("@starttime").Value = starttimeInput.Text
  15.  
  16.         command.Parameters.Add("@address", SqlDbType.VarChar)
  17.         command.Parameters("@address").Value = txtAddress.Text
  18.  
  19.         command.Parameters.Add("@endtime", SqlDbType.VarChar)
  20.         command.Parameters("@endtime").Value = endtimeInput.Text
  21.  
  22.  
  23.         command.Parameters.Add("@duration", SqlDbType.VarChar)
  24.         command.Parameters("@duration").Value = duration.Text
  25.  
  26.         Try
  27.             connection.Open()
  28.             Dim rowsAffected As Integer = command.ExecuteNonQuery()
  29.  
  30.         Catch ex As Exception
  31.             myErrorMessageLabel.Text = ex.Message
  32.         End Try
  33.     End Using
-Frinny
Oct 7 '10 #10
dougancil
347 100+
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

Expand|Select|Wrap|Line Numbers
  1. <asp:DropDownList ID="OperatorDropdown" runat="server" 
  2.             DataSourceID="SqlDataSource1" DataTextField="employeenumber" 
  3.             DataValueField="employeenumber" Height="23px" Width="130px">
  4.         </asp:DropDownList>
  5.         <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  6.             ConnectionString="<%$ ConnectionStrings:MDRConnectionString %>" 
  7.             SelectCommand="SELECT [employeenumber] FROM [Employees]">
  8.         </asp:SqlDataSource>
  9.  
While the other two are not.
Oct 7 '10 #11
Frinavale
9,735 Expert Mod 8TB
I haven't worked with bound DropDownLists in the past but I would think that you could just access the OperatorDropdown.SelectedItem.Value property and set the parameter's value to it... like I did above.
Oct 7 '10 #12
dougancil
347 100+
so like this for the databound dropdown?

Expand|Select|Wrap|Line Numbers
  1. command.Parameters.Add("@employeenumber", SqlDbType.Varchar)
  2.         command.Parameters("@employeenumber".value = OperatorDropdown.SelectedItem.Value
  3.  
and like this for the non-databound?

Expand|Select|Wrap|Line Numbers
  1. command.Parameters.Add("@code", SqlDbType.Varchar)
  2.         command.Parameters("@code").Value = listitem.value
  3.  
Oct 7 '10 #13
Frinavale
9,735 Expert Mod 8TB
You're missing a")" in your code. It should be....
Expand|Select|Wrap|Line Numbers
  1. command.Parameters.Add("@employeenumber", SqlDbType.Varchar)
  2. 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 "SelectedItem" property accordingly. In your case either OperatorDropdown.SelectedItem.Value or OperatorDropdown.SelectedItem.Text will work.
Oct 7 '10 #14
dougancil
347 100+
Frinny,

What about for the non-bound dropdown? Is that correct? Oh and thank you for pointing out the missing ")". I corrected that.
Oct 7 '10 #15
Frinavale
9,735 Expert Mod 8TB
Same thing for a non-bound DropDownList :)
You add ListItems to a DropDownList and they work the same way because ListItems have Text and Values.

-Frinny
Oct 7 '10 #16
dougancil
347 100+
Frinny,

Is there a way that I can insert a datediff sql statement here to determine the difference between the starttimeInput and the endtimeInput boxes here?
Oct 7 '10 #17
Frinavale
9,735 Expert Mod 8TB
Sure.

Retrieve the text from the TextBoxes and create 2 DateTime variables (one for the start time and one for the end time).

Use the DateTime.TryParse() method populate the DateTime variables.

Then subtract the Start time from the End Time to get the "delta time" (the change in time).

Like this:

Expand|Select|Wrap|Line Numbers
  1. Dim startTime As DateTime
  2. DateTime.TryParse("9:00", startTime)
  3. 'you could also use: DateTime.TryParse("9:00 AM", startTime)
  4.  
  5. Dim endTime As DateTime
  6. DateTime.TryParse("17:00", endTime)
  7. 'you could also use: DateTime.TryParse("5:00 PM", endTime)
  8.  
  9. Dim timeInterval As TimeSpan = endTime - startTime
  10.  
  11. Dim deltaHours As Integer = timeInterval.Hours
Once calculated, you can store this information in your database.
Oct 7 '10 #18
dougancil
347 100+
Frinny,

So where you have this

DateTime.TryParse ("9:00", startime)

Is that passing the variable for the textbox into this?
Oct 7 '10 #19
Frinavale
9,735 Expert Mod 8TB
That will Try to convert the string "9:00" into a DateTime variable.

The TryParse method will return false if it can't parse the string into a DateTime type.

This is yet another layer of data validation that you can add to your application.

So what you want to do is pass the time that the user entered into the TryParse method instead of "9:00" (a hard coded string).
Oct 7 '10 #20
dougancil
347 100+
So then would I put the value of starttime.text there since that's where I'll be getting the data from, instead of "9:00?"
Oct 7 '10 #21

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Arda | last post by:
Hi all, I tried to connect a database(SQL) by both VS 2003 interface tools and normal typing. When I make the connection in local Web project it doesn't work and gives an error like this; ...
3
by: Makarand Keer | last post by:
Hi all Gurus I have asp.net application where I am creating background process using Threading. My threading involves invoking method which in turn gets some data from SQL server using Windows...
4
by: farhan | last post by:
Please let me know code used to simply connect a database and then add, delete, update records in asp.net using vb.net.
0
by: spiewak | last post by:
Is this possible to connect do the Database Engine (on sql server 2005 on XP platorm - file *.mdf (not mobile *.sdf)) form win CE 5.0 ? I tried to do this ConnectionStringSQLServerCE = "Data...
0
by: spiewak | last post by:
Is this possible to connect do the Database Engine (on sql server 2005 on XP platorm - file *.mdf (not mobile *.sdf)) from win CE 5.0 ? I tried to do this : ConnectionStringSQLServerCE = "Data...
0
by: hussainiyad | last post by:
hi to all this is hussain i need ur help. in a datagrid there r two textboxes and a button and a label, if i type any value in that textboxes and click the button if the values r equal then the msg...
2
xtianixm
by: xtianixm | last post by:
How To Connect Mysql Database Through Network!
1
by: sravani1 | last post by:
I am new to the php. i wrote the code to connect to the database. I will use the following code. <?php $con = mysql_connect("localhost","root","root"); if (!$con) { die('Could not connect:...
1
debasisdas
by: debasisdas | last post by:
This is a sample code for taking backup and restore of access database Dim DBTempSource As Database Dim DBTempDestination As Database Dim RecTempSource As Recordset Dim RecTempDestination...
0
by: ezrockgw | last post by:
i want to make an application in j2me so that it interacts with database and keeps updating it. How can i connect my mobile to the pc which has the database?...Will it be through bluetooth which i...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.