can't read data from database in asp.net using vb - asp.net

i am learning asp.net using vb,i am working on college assignment
i have to read data from msaccess and show record in label
basically i am doing 'search' operation
here is the code
Public Class WebForm2
Inherits System.Web.UI.Page
Dim connection As New OleDb.OleDbConnection
Dim sname, lname, city, subj, gender, hobbies, religion As String
Dim age, phone As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
connection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\himzz\Documents\Database1.accdb;")
connection.Open()
If Not IsPostBack Then
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
sname = TextBox1.Text
lname = TextBox2.Text
age = TextBox3.Text
city = TextBox4.Text
phone = TextBox5.Text
subj = DropDownList1.SelectedValue
If RadioButton1.Checked Then
gender = "male"
ElseIf RadioButton2.Checked Then
gender = "female"
Else
gender = "other"
End If
'If CheckBox1.Checked And CheckBox2.Checked And CheckBox3.Checked Then
' hobbies = "cricket swimming tennis "
'End If
If CheckBox1.Checked Then
hobbies += "cricket "
End If
If CheckBox2.Checked Then
hobbies += "swimming "
End If
If CheckBox3.Checked Then
hobbies += " tennis "
End If
religion = DropDownList2.SelectedValue
Try
Dim q As String = "insert into stud (sname,lname,age,city,phone,subj,gender,hobbies,religion) values('" & sname & "','" & lname & "','" & age & "','" & city & "','" & phone & "','" & subj & "','" & gender & "','" & hobbies & "','" & religion & "' )"
Dim cmd As New OleDb.OleDbCommand(q, connection)
cmd.ExecuteNonQuery()
MsgBox("submitted")
Catch ex As Exception
MsgBox("error")
End Try
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
Protected Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim q As String = "select lname from stud where sname='" & sname & "' "
Dim cmd As New OleDb.OleDbCommand(q, connection)
Dim reader As OleDb.OleDbDataReader
reader = cmd.ExecuteReader()
While reader.Read()
(tried this but not worked) ' Label12.Text = " " & reader("sname")
(tried this also but not worked)' Label12.Text =reader.Item("sname").ToString()
(not working) Label12.Text = reader("sname").ToString
'Label13.Text = "age " & reader("age")
'Label14.Text = "city " & reader("city")
'Label15.Text = "phone no " & reader("phone")
'Label16.Text = "subject " & reader("subj")
'Label17.Text = "Gedner " & reader("gender")
'Label18.Text = "Hobbies " & reader("hobbies")
'Label19.Text = "Religion " & reader("religion")
End While
reader.Close()
End Sub
End Class

Related

"Number of query values and destination fields are not the same" error on INSERT

Imports System.Data
Imports System.Data.OleDb
Public Class form7
Dim inc As Integer
Dim con As New OleDb.OleDbConnection
Dim cmd As OleDbCommand
Dim dbprovider As String
Dim dbsource As String
Dim str As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim TotalRows As Integer
Dim ID_Number As Integer
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Bank\db1.accdb ")
con.Open()
Dim cmd As New OleDbCommand("SELECT COUNT(*) FROM accountsTable", con)
Dim totalRows As Long = CInt(cmd.ExecuteScalar())
cmd.ExecuteNonQuery()
TextBox1.Text = totalRows + 1000
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Form5.Show()
dbprovider = "Provider=Microsoft.ACE.OLEDB.12.0; dbsource=Data Source=D:\Bank\db1.accdb"
MsgBox("Database is now open")
str = "Insert into accountsTable (Account_Number, First_Name, Midle_Name, Last_Name, Date_of_birth, Occupation, Age, Marital_Status, Address, City, Country, State, Account_Type, Pin_Code, Mobile_Number, Email_ID, Opening_Balance) values ('" &
TextBox1.Text & "','" &
TextBox2.Text & "','" &
TextBox3.Text & "','" &
TextBox4.Text & "','" &
DateTimePicker1.Value & "','" &
TextBox6.Text & "','" &
TextBox7.Text & "','" &
TextBox8.Text & "','" &
TextBox9.Text & "','" &
ComboBox1.Text & "','" &
ComboBox2.Text & "','" &
ComboBox3.Text & "','" &
ComboBox4.Text & "','" &
TextBox10.Text & "','" &
TextBox11.Text & "','" &
TextBox12.Text & "','" &
TextBox13.Text & "','" & "')"
cmd = New OleDb.OleDbCommand(str, con)
cmd.ExecuteNonQuery()
MsgBox("Record is inserted")
con.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
DateTimePicker1.Value = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
TextBox9.Text = ""
ComboBox1.Text = ""
ComboBox2.Text = ""
ComboBox3.Text = ""
ComboBox4.Text = ""
TextBox10.Text = ""
TextBox11.Text = ""
TextBox12.Text = ""
TextBox13.Text = ""
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
Form3.Show()
End Sub
End Class
The error happens here :
cmd = New OleDb.OleDbCommand(str, con)
cmd.ExecuteNonQuery() ' <-- error here
MsgBox("Record is inserted")
con.Close()
You have 17 columns in your columns list, but you are adding an extra (18th) zero-length string value onto the end of your VALUES list:
TextBox13.Text & "','" & "')"
^^^^^^^^
You really should be using a parameterized query, something more like this:
str =
"Insert into accountsTable (Account_Number, First_Name, Midle_Name, Last_Name, Date_of_birth, Occupation, Age, Marital_Status, Address, City, Country, State, Account_Type, Pin_Code, Mobile_Number, Email_ID, Opening_Balance) " &
"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
cmd = New OleDb.OleDbCommand(str, con)
cmd.Parameters.AddWithValue("?", TextBox1.Text)
cmd.Parameters.AddWithValue("?", TextBox2.Text)
cmd.Parameters.AddWithValue("?", TextBox3.Text)
cmd.Parameters.AddWithValue("?", TextBox4.Text)
cmd.Parameters.AddWithValue("?", DateTimePicker1.Value)
cmd.Parameters.AddWithValue("?", TextBox6.Text)
cmd.Parameters.AddWithValue("?", TextBox7.Text)
cmd.Parameters.AddWithValue("?", TextBox8.Text)
cmd.Parameters.AddWithValue("?", TextBox9.Text)
cmd.Parameters.AddWithValue("?", ComboBox1.Text)
cmd.Parameters.AddWithValue("?", ComboBox2.Text)
cmd.Parameters.AddWithValue("?", ComboBox3.Text)
cmd.Parameters.AddWithValue("?", ComboBox4.Text)
cmd.Parameters.AddWithValue("?", TextBox10.Text)
cmd.Parameters.AddWithValue("?", TextBox11.Text)
cmd.Parameters.AddWithValue("?", TextBox12.Text)
cmd.Parameters.AddWithValue("?", TextBox13.Text)
cmd.ExecuteNonQuery()
Note that if some of those TextBox controls may be empty then you'll have to check the length of their .Text properties and possibly insert a null value instead. For example, for "Opening_Balance" you may need to do something like
If TextBox13.Text.Length = 0 Then
cmd.Parameters.AddWithValue("?", DBNull.Value)
Else
cmd.Parameters.AddWithValue("?", Convert.ToDecimal(TextBox13.Text))
End If

oleDbexception was unhandled by user code

I cannot see the added data in the data table when debugging starts it doesn't have any error but when I click button1 it shows me errors (unhandled by user code) unclosed quotation mark after the character string ')'
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As OleDbConnection
Dim strInsert As String
Dim cmdInsert As OleDbCommand
Dim vt As Byte, vm As Byte
Dim sze As Byte
con = New OleDbConnection("Integrated Security=SSPI;Packet Size=4096;Data Source=.;Tag with column collation when possible=False;Initial Catalog=borjara;Use Procedure for Prepare=1;Auto Translate=True;Persist Security Info=False;Provider=SQLOLEDB.1;Workstation ID=ABDI;Use Encryption for Data=False")
If RadioButton4.Checked = True Then vt = 0
If RadioButton5.Checked = True Then vt = 1
If RadioButton6.Checked = True Then vm = 0
If RadioButton7.Checked = True Then vm = 1
If RadioButton8.Checked = True Then vm = 2
If RadioButton9.Checked = True Then szs = 1
If RadioButton10.Checked = True Then szs = 0
con.Open()
strInsert = "insert Into t1(jens) Values (" & DropDownList1.SelectedItem.Text & "')"
cmdInsert = New OleDbCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()//error is here
con.Close()
con.Open()
strInsert = "insert Into t1(bazsho) Values (" & DropDownList2.SelectedItem.Text & "')"
cmdInsert = New OleDbCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()
con.Close()
con.Open()
strInsert = "insert Into t1(name and lastname,email,number,address,lenght,wideth,turi,glasstype,glass) Values (" & n & ",'" & TextBox1.Text(+" / " + TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "'," & vt & "," & vm & "," & szs & "')")
cmdInsert = New OleDbCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()
con.Close()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
End Sub
End Class
It looks like there is no opening quote in the values of the first two Inserts.

How to insert the values of 3 droplists into a single column of an MS Access database, using asp.net

In my project i display an 3 droplists (Daydrplist, MonthDropList, YearDropList). When the user selects the values and clicks the button the values should be inserted to the access database in the BirthDate column of the Teacher table.
How can I do that?
Protected Sub NextBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles NextBtn.Click
con = New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\user\Desktop\web programming\\IULWebInformationSystem1\IULWebInformationSystem1\App_Data\IUlDB.accdb;Persist Security Info=True"
con.Open()
sqlquery = "insert into Teacher values ('" & FirstNameTxtBox.Text & "','" & MiddelNameTxtBox.Text & "','" & LastNameTxtBox.Text & "','" & POBTxtBox.Text & "','" & NationalityDropList.SelectedValue & "','" & Gendrplist.SelectedValue & "')"
cmd = New OleDbCommand(sqlquery, con)
cmd.ExecuteNonQuery()
con.Close()
FirstNameTxtBox.Text = ""
MiddelNameTxtBox.Text = ""
LastNameTxtBox.Text = ""
POBTxtBox.Text = ""
NationalityDropList.SelectedValue = ""
Gendrplist.SelectedValue = ""
lblmsg2.Text = "Personal Information was Added Successfully"
lblmsg2.Visible = True
Response.Redirect("PersonalAddress.aspx")
End Sub

How to save uploaded .csv file into SQL Server Management database using asp.net

This is a sample of my code. I am using Microsoft Visual Studio 2010, with asp.net version 2.0, when the user clicks the import button, the csv file will be saved in the database. My code contains errors, and I do not know how to solve them, please help!
protected void btnImport_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection (#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
StreamReader Sr = new StreamReader("filepath");
string line;
while ((line = Sr.ReadLine()) != null)
{
line = Sr.ReadLine();
}
const string SQL = "INSERT INTO [Guest] ([GuestName], [IC_Number], [EventName], [GuestID]) VALUES (#GuestName, #IC_Number, #EventName, #GuestID)";
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("#GuestName", Sr);
cmd.Parameters.AddWithValue("#IC_Number", Sr);
cmd.Parameters.AddWithValue("#EventName", Sr);
cmd.Parameters.AddWithValue("#GuestID", Sr);
con.Open();
cmd.ExecuteNonQuery();// 1,0 will determine whether line is inserted, upload has error...
con.Close();
}
Your insert query must be in your while
Sr is not your parameter, but line which contains an array of your data. So it is probably line[i] that you must give to AddWithValue
You are assigning line = Sr.ReadLine() twice in your code, just do it in the while
So try something like this:
protected void btnImport_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection (#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
con.Open();
StreamReader Sr = new StreamReader("filepath");
string line;
string SQL = "INSERT INTO [Guest] ([GuestName], [IC_Number], [EventName], [GuestID]) VALUES (#GuestName, #IC_Number, #EventName, #GuestID)";
while ((line = Sr.ReadLine()) != null)
{
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("#GuestName", line[0]);
cmd.Parameters.AddWithValue("#IC_Number", line[1]);
cmd.Parameters.AddWithValue("#EventName", line[2]);
cmd.Parameters.AddWithValue("#GuestID", line[3]);
cmd.ExecuteNonQuery();// 1,0 will determine whether line is inserted, upload has error...
}
con.Close();
}
i have done something like this however it was xls files i needed to import but not much differentce really, here is the code i used
Protected Sub ButtonImport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonImport.Click
PanelView.Visible = False
PanelUpload.Visible = False
PanelImport.Visible = True
LabelImport.Text = "" 'reset to blank
Dim xConnstr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & (Server.MapPath("SiteTemplate.xls")) & ";" & _
"Extended Properties=Excel 8.0"
' create your excel connection object using the connection string
Dim objXConn As New System.Data.OleDb.OleDbConnection(xConnstr)
objXConn.Open()
Dim objCommand As New OleDbCommand("SELECT * FROM [importsites$]", objXConn)
'Creating the data reader
Dim reader As OleDbDataReader
reader = objCommand.ExecuteReader()
Dim counter As Integer = 0
While reader.Read()
counter = counter + 1
Dim siteID As Integer = 0
Dim siteIWSref As String = Convert.ToString(reader("siteIWSref"))
If siteIWSref = "" Then
siteIWSref = "."
End If
Dim siteUPRN As String = Convert.ToString(reader("siteUPRN"))
If siteUPRN = "" Then
siteUPRN = "."
End If
Dim siteName As String = Convert.ToString(reader("siteName"))
Dim siteAdd1 As String = Convert.ToString(reader("siteAdd1"))
Dim siteAdd2 As String = Convert.ToString(reader("siteAdd2"))
Dim siteAdd3 As String = Convert.ToString(reader("siteAdd3"))
Dim sitePcode As String = Convert.ToString(reader("sitePcode"))
Dim siteContact As String = Convert.ToString(reader("siteContact"))
Dim siteContactPos As String = Convert.ToString(reader("siteContactPos"))
Dim siteContactTel As String = Convert.ToString(reader("siteContactTel"))
Dim siteDesc As String = Convert.ToString(reader("siteDesc"))
Dim siteCompany As Integer = CInt(CompanyDD.SelectedValue)
Dim siteOccupants As String = Convert.ToString(reader("siteOccupants"))
Dim siteType As String = Convert.ToString(reader("siteType"))
siteID = ImportIntotblSite(siteIWSref, siteUPRN, siteName, siteAdd1, siteAdd2, siteAdd3, sitePcode, siteContact, siteContactPos, siteContactTel, siteDesc, siteCompany, siteOccupants, siteType)
LabelImport.Text &= siteID & siteIWSref & " " & siteUPRN & " " & siteName & " " & siteAdd1 & " " & siteAdd2 & " " & siteAdd3 & " " & " " & sitePcode & " " & siteContact & " " & siteContactPos & " " & siteContactTel & " " & siteDesc & " " & siteCompany & " " & siteOccupants & " " & " " & siteType & "<br>"
End While
reader.Close()
objCommand.Dispose()
objXConn.Close()
btnBack.Enabled = True
btnBack.Visible = True
btnSave.Visible = True
btnSave.Enabled = True
End Sub
Protected Function ImportIntotblSite(ByVal siteIWSref As String, ByVal siteUPRN As String, ByVal siteName As String, ByVal siteAdd1 As String, ByVal siteAdd2 As String, ByVal siteAdd3 As String, ByVal sitePcode As String, ByVal siteContact As String, ByVal siteContactPos As String, ByVal siteContactTel As String, ByVal siteDesc As String, ByVal siteCompany As Integer, ByVal siteOccupants As String, ByVal siteType As String) As Integer
siteIWSref = Left(siteIWSref, 20)
siteUPRN = Left(siteUPRN, 20)
siteName = Left(siteName, 60)
siteAdd1 = Left(siteAdd1, 50)
siteAdd2 = Left(siteAdd2, 50)
siteAdd3 = Left(siteAdd3, 50)
sitePcode = Left(sitePcode, 10)
siteContact = Left(siteContact, 35)
siteContactPos = Left(siteContactPos, 35)
siteContactTel = Left(siteContactTel, 20)
siteDesc = Left(siteDesc, 220)
siteOccupants = Left(siteOccupants, 120)
siteType = Left(siteType, 35)
Dim siteID As Integer = 0
Try
Dim SSAdapter As New importSitesDataSetTableAdapters.tblSiteTableAdapter
Dim SSDataTable As importSitesDataSet.tblSiteDataTable = Nothing
SSDataTable = SSAdapter.GetDataByNumbers(siteIWSref, siteName, siteCompany)
If siteName = "" Then
siteName = ""
End If
'see if the category already exists in the table, if not insert it
If Not SSDataTable Is Nothing Then
If siteName = "" Then
LabelImport.Text = LabelImport.Text & _
"<font color=red>ERROR: BLANK SITE NAME: ROW NOT IMPORTED : " & _
"ID: " & siteID & _
" Name: " & siteName & " " & siteCompany & ".</font><br>"
ElseIf SSDataTable.Rows.Count > 0 Then
If Not SSDataTable(0).siteID = Nothing Then
siteID = SSDataTable(0).siteID
LabelImport.Text = LabelImport.Text & _
"<font color=blue> Recorded already exists : " & _
"ID: " & siteID & _
"Name: " & siteName & " " & siteCompany & ".</font><br>"
End If
End If
End If
If siteID = 0 And siteName <> "" Then
siteID = Convert.ToInt32(SSAdapter.InsertQuery(siteIWSref, siteUPRN, siteName, siteAdd1, siteAdd2, siteAdd3, sitePcode, siteContact, siteContactPos, siteContactTel, siteDesc, siteCompany, siteOccupants, siteType))
LabelImport.Text = LabelImport.Text & _
"<font color=green> ROW SUCCESSFULLY IMPORTED: " & _
" ID: " & siteID & _
" Name: " & siteName & " " & siteCompany & ".</font><br>"
End If
Return siteID
'SSAdapter.Dispose()
Catch ex As Exception
LabelImport.Text = LabelImport.Text & "<font color=red>" & ex.ToString & ".</font><br>"
Return 0
End Try
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'TableButtons.Visible = False
'FileUploadExcel.Visible = False
'PanelUpload.Visible = False
btnYes.Visible = False
btnNo.Visible = False
btnBack.Enabled = False
btnBack.Visible = False
ButtonView.Enabled = False
ButtonImport.Enabled = False
btnSave.Visible = False
btnSave.Enabled = False
End Sub
try this and let me know how you get on.
there is a brilliant example of how to upload information onto an sql server at:
http://www.shiningstar.net/aspnet_articles/DataSet/DataSetProject.aspx
i am aware its for excel however surely there cant be that much difference.

I'm trying to insert info into two tables on a single btnclick. Its writing to only one table still. Can't see what I'm missing. [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If (Not Page.IsPostBack) Then
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("databob.mdb")
Dim strSQLCommand As String
strSQLCommand = "SELECT Customers.* FROM Customers ORDER BY Customers.CustomerID DESC;"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
End If
If (Not Page.IsPostBack) Then
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("databob.mdb")
Dim strSQLCommand2 As String
strSQLCommand2 = "SELECT CardType, CardNumber, Valid, Expiry, 3Digit FROM Orders ORDER BY Orders.OrderID DESC;"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand2, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
End If
End Sub
Protected Sub btnContinue_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim strFirstName As String
Dim strLastName As String
Dim strAddress As String
Dim strPostcode As String
Dim strHomeNo As String
Dim strMobileNo As String
Dim strEmail As String
Dim strCardType As String
Dim strCardNumber As String
Dim strValid As String
Dim strExpiry As String
Dim str3Digit As String
strFirstName = tbxFirstName.Text
strLastName = tbxLastName.Text
strAddress = tbxAddress.Text
strPostcode = tbxPostcode.Text
strHomeNo = tbxHomeNo.Text
strMobileNo = tbxMobileNo.Text
strEmail = tbxEmail.Text
strCardType = ddlCardType.Text
strCardNumber = tbxCardNumber.Text
strValid = tbxValid.Text
strExpiry = tbxExpiry.Text
str3Digit = tbx3Digit.Text
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("databob.mdb")
Dim strSQLCommand As String
strSQLCommand = "INSERT INTO Customers(FirstName, LastName, Address, Postcode, HomeNo, MobileNo, Email) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strAddress & "', '" & strPostcode & "', '" & strHomeNo & "', '" & strMobileNo & "', '" & strEmail & "');"
Dim strSQLCommand2 As String
strSQLCommand2 = "INSERT INTO Orders(CardType, CardNumber, Valid, Expiry, 3Digit) " & _
"Values ('" & strCardType & "', '" & strCardNumber & "', '" & strValid & "', '" & strExpiry & "', '" & str3Digit & "');"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "SELECT Customers.* FROM Customers ORDER BY Customers.CustomerID DESC;"
strSQLCommand2 = "SELECT Orders.* FROM Orders ORDER BY Orders.OrderID DESC;"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
tbxFirstName.Text = ""
tbxLastName.Text = ""
tbxAddress.Text = ""
tbxPostcode.Text = ""
tbxHomeNo.Text = ""
tbxMobileNo.Text = ""
tbxEmail.Text = ""
ddlCardType.Text = ""
tbxCardNumber.Text = ""
tbxValid.Text = ""
tbxExpiry.Text = ""
tbx3Digit.Text = ""
End Sub
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
That executes the first one but you do not do it again for strSQLCommand2
-- as an aside please look into parameterization of your queries. You are just asking for sql injection with that.
INSERT INTO Orders(Orders( looks a tad fishy to me (unless that's a C&P error posting this question)
And as Ken points out, if you're wanting to run both queries (rather than replace one with the other), you probably want:
strSQLCommand = strSQLCommand & " INSERT INTO Orders(CardType, CardNumber, Valid, Expiry, 3Digit) " & _
Your problem is that you are trying to use same string variable to hold both sqls, in fact you are overwriting the first one with the second one, modify your code like this
Dim strSQLCommand As String
Dim strSQLCommand2 As String
strSQLCommand = "INSERT INTO Customers(FirstName, LastName, Address, Postcode, HomeNo, MobileNo, Email) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strAddress & "', '" & strPostcode & "', '" & strHomeNo & "', '" & strMobileNo & "', '" & strEmail & "');"
strSQLCommand2 = "INSERT INTO Orders(Orders(CardType, CardNumber, Valid, Expiry, 3Digit) " & _
"Values ('" & strCardType & "', '" & strCardNumber & "', '" & strValid & "', '" & strExpiry & "');"
and then afterwards you need to execute both statements, also you should add a transaction, something like this
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objTrans As System.Data.OleDb.OleDbTransaction;
objTrans=objOleDbConnection.BeginTransaction();
try
{
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbCommand.CommandText =strSQLCommand2;
objOleDbCommand.ExecuteNonQuery()
objTrans.Commit();
}
catch{Exception ex}
{
objTrans.Rollback();
}
finally
{
objOleDbConnection.Close()
}
Just pulling it out of my head, can be a typo on it, but you can get the idea

Resources