Insert data in MySQL - asp.net

When I click on the button it should insert this data in database, but this doesn't happen. It just shows me a MsgBox and doesn't load the insert order.
Private Sub Button1_Click (sender As Object, e As EventArgs) Handles Button1.Click
Dim s As MySqlConnection = servconn("localhost", "root", "123")
If s.State = ConnectionState.Connecting Then
Using insert As MySqlCommand = s.CreateCommand
insert.Connection = s
insert.CommandType = CommandType.Text
insert.CommandText = "insert INTO exam.app (ID, UserName, Email, address) VALUES (NULL, '" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "')"
ID = Convert.ToInt32(insert.ExecuteScalar())
End Using
End If
MsgBox("Inserted commpleted")
End Sub

Related

VB.net Input string was not in a correct format

Here is a picture of error
Keep Getting error
input string was not in correct format
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
My guess is the CInt but it works in another similar application . Not sure what is going on . Here is the code
product-detail.aspx.vb
Imports System.Data
Imports System.Data.SqlClient
Partial Class HTML_Product_Detail
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("ProductID") <> "" Then
Dim strConn As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
Dim connProduct As SqlConnection
Dim cmdProduct As SqlCommand
Dim drProduct As SqlDataReader
Dim strSQL As String = "Select * from Product Where ProductID = " & Request.QueryString("ProductID")
connProduct = New SqlConnection(strConn)
cmdProduct = New SqlCommand(strSQL, connProduct)
connProduct.Open()
drProduct = cmdProduct.ExecuteReader(CommandBehavior.CloseConnection)
'drProduct.Read()
If drProduct.Read() Then
lblProductName.Text = drProduct.Item("ProductName")
lblProductDescription.Text = drProduct.Item("ProductName")
lblPrice.Text = drProduct.Item("Price")
lblProductNo.Text = drProduct.Item("ProductNo")
imgProduct.ImageUrl = "images/product-detail/" + Trim(drProduct.Item("ProductNo")) + ".jpg"
End If
End If
End Sub
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
' *** get product price
Dim dr As SqlDataReader
Dim strSQLStatement As String
Dim cmdSQL As SqlCommand
Dim strConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionStringOnlineStore").ConnectionString
strSQLStatement = "SELECT * FROM Product WHERE ProductNo = '" & lblProductNo.Text & "'"
Dim conn As New SqlConnection(strConnectionString)
conn.Open()
cmdSQL = New SqlCommand(strSQLStatement, conn)
dr = cmdSQL.ExecuteReader()
Dim decPrice As Decimal
If dr.Read() Then
decPrice = dr.Item("Price")
End If
conn.Close()
'*** get CartID
Dim strCartID As String
If HttpContext.Current.Request.Cookies("CartID") Is Nothing Then
strCartID = GetRandomCartIDUsingGUID(10)
Dim CookieTo As New HttpCookie("CartID", strCartID)
HttpContext.Current.Response.AppendCookie(CookieTo)
Else
Dim CookieBack As HttpCookie
CookieBack = HttpContext.Current.Request.Cookies("CartID")
strCartID = CookieBack.Value
End If
'Check if this product already exist in the cart
Dim dr2 As SqlDataReader
Dim strSQLStatement2 As String
Dim cmdSQL2 As SqlCommand
strSQLStatement2 = "SELECT * FROM cart WHERE CartID ='" & strCartID & "' and ProductID = '" & Trim(lblProductNo.Text) & "'"
'Reponse.Write(strSQlStatement2)
Dim conn2 As New SqlConnection(strConnectionString)
cmdSQL2 = New SqlCommand(strSQLStatement2, conn2)
conn2.Open()
dr2 = cmdSQL2.ExecuteReader()
If dr2.Read() Then
Dim intQuantityNew As Integer = dr2.Item("Quantity") + CInt(tbQuantity.Text)
strSQLStatement = ""
cmdSQL = New SqlCommand(strSQLStatement, conn)
Else
Dim dr3 As SqlDataReader
Dim strSQLStatement3 As String
Dim cmdSQL3 As SqlCommand
strSQLStatement = "INSERT INTO Cart (CartID, ProductID, ProductName, Quantity, Price) values('" & strCartID & "', '" & Trim(lblProductNo.Text) & "', '" & lblProductName.Text & "', " & CInt(tbQuantity.Text) & ", " & decPrice & ")"
'Response.Write(strSQLStatement3)
Dim conn3 As New SqlConnection(strConnectionString)
conn3.Open()
cmdSQL3 = New SqlCommand(strSQLStatement3, conn3)
dr3 = cmdSQL3.ExecuteReader()
End If
'Response.Redirect("ViewCart.aspx")
End Sub
Public Function GetRandomCartIDUsingGUID(ByVal length As Integer) As String
'Get the GUID
Dim guidResult As String = System.Guid.NewGuid().ToString()
'Remove the hyphens
guidResult = guidResult.Replace("-", String.Empty)
'Make sure length is valid
If length <= 0 OrElse length > guidResult.Length Then
Throw New ArgumentException("Length must be between 1 and " & guidResult.Length)
End If
'Return the first length bytes
Return guidResult.Substring(0, length)
End Function
End Class
The issue is almost certainly here:
CInt(tbQuantity.Text)
The exception information even says:
Conversion from string "" to type 'Integer' is not valid.
You cannot convert a String to an Integer if the text doesn't represent a valid value and an empty string obviously doesn't represent a number. Validate the data first or else validate and convert in one go using Integer.Tryparse.

database cannot update textbox value in vb.net

I am doing a update profile in a web application using vb.net. At first I read the database and put the data into the textbox, then i change the data inside the textbox and click the 'update' button. The problem is when i click the button, it won't update the latest value that i typed into the textbox. It will still update the value where i read from database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim item1 As String = CType(Session.Item("UserAccount"), String)
txtUsername.Enabled = False
conn.Open()
sql1 = "Select * From [Users] WHERE username='" & item1 & "'"
cmd = New SqlCommand(sql1, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
txtUsername.Text = dr.Item("username")
password = dr.Item("password")
txtFirstName.Text = dr.Item("firstname")
txtLastName.Text = dr.Item("lastname")
txtDob.Text = dr.Item("dob")
txtEmail.Text = dr.Item("email")
txtNumber.Text = dr.Item("phone")
txtAddress.Text = dr.Item("address")
End If
dr.Close()
conn.Close()
End Sub
'above this image is how i read from the database.
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim errFirstName As Boolean = True
Dim errLastName As Boolean = True
Dim errCPassword As Boolean = True
Dim errNPassword As Boolean = True
Dim errDob As Boolean = True
Dim errEmail As Boolean = True
Dim errNumber As Boolean = True
Dim errAddress As Boolean = True
Dim newFName, newLName, newPassword, newAddress, newNumber, newEmail, newDob As String
If txtFirstName.Text = "" Then
txtFirstName.BackColor = Drawing.Color.LightPink
lblFirstName.Text = "cannot be empty"
ElseIf Not Regex.Match(txtFirstName.Text, "^[a-zA-Z_ ]*$", RegexOptions.IgnoreCase).Success Then
.
.
.
This is the 'Update' button click.
Here is where i do all the validation for the value in textbox
If errNPassword = False And errCPassword = False And errFirstName = False And errLastName = False And errDob = False And errEmail = False And errNumber = False And errAddress = False Then
conn.Open()
sql2 = "Update [Users] Set password='" & newPassword & "', firstname='" & newFName & "', lastname='" & newLName & "', dob='" & newDob & "', address='" & newAddress & "', email='" & newEmail & "', phone='" & newNumber & "' WHERE username='" & txtUsername.Text & "'"
cmd = New SqlCommand(sql2, conn)
cmd.ExecuteNonQuery()
conn.Close()
Response.Redirect(String.Format("~/index.aspx?"))
Else
Dim message As String = "Please correct the error above"
Dim sb As New System.Text.StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("window.onload=function(){")
sb.Append("alert('")
sb.Append(message)
sb.Append("')};")
sb.Append("</script>")
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb.ToString())
Exit Sub 'break
End If
This is how i update the value of textbox to my database where the username is match.
Your page is posting back and running the same code, you have to add If Not IsPostBack to Page_Load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack
Dim item1 As String = CType(Session.Item("UserAccount"), String)
txtUsername.Enabled = False
conn.Open()
sql1 = "Select * From [Users] WHERE username='" & item1 & "'"
cmd = New SqlCommand(sql1, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
txtUsername.Text = dr.Item("username")
password = dr.Item("password")
txtFirstName.Text = dr.Item("firstname")
txtLastName.Text = dr.Item("lastname")
txtDob.Text = dr.Item("dob")
txtEmail.Text = dr.Item("email")
txtNumber.Text = dr.Item("phone")
txtAddress.Text = dr.Item("address")
End If
dr.Close()
conn.Close()
End If
End Sub

Can't UPDATE a large image size that was INSERTed in the database in asp.net

Here is the problem, when I insert an image (let's call it Data A) which is 1.32MB, it will be inserted successfully. But if I will insert again Data A(but it will update now because i used UPSERT, see my code), it will not be updated and it will result to connection time out.
But when i insert another data (Data B) which is only 4KB, it will also be inserted successfully and if I will insert again into it(which is update), it will be updated successfully. What can I do? I cannot understand the problem. I already made my command timeout for 2 mins but nothing happened and it just loaded forever. I also used sql transaction but it did nothing.
Here is my code:
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim strConnString As String = DataSource.ConnectionString
Using con As New SqlConnection(strConnString)
Dim SQLStr As String
Dim base64String = TextArea1.Value
Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
Dim FileSizeOfIMG As String
FileSizeOfIMG = imageBytes.Length
Dim ImageTypeDataOfImage As New SqlParameter("#Data", SqlDbType.Image)
ImageTypeDataOfImage.Value = imageBytes
SQLStr = "SELECT 1 FROM [Patient_Data].[dbo].[tbPatientImage] where HospNum='" & Session.Item("HospNum") & "'" & _
" and IDNum='" & Session.Item("IDNum") & "' and FileType= '" & lblHeader.Text & "'"
Dim cmd As New SqlCommand(SQLStr, con)
cmd.Connection = con
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
SQLStr = "UPDATE [Patient_Data].[dbo].[tbPatientImage] SET PatImage= #Data, FileSize= '" & FileSizeOfIMG.ToString & "' , TransDate = GetDate() where HospNum='" & Session.Item("HospNum") & "' and IDNum='" & Session.Item("IDNum") & "' and FileType= '" & lblHeader.Text & "'"
Else
SQLStr = "INSERT INTO [Patient_Data].[dbo].[tbPatientImage](HospNum,IDNum, DoctorID, PatImage , FileType, FileName, FileSize , TransDATE) " & _
" VALUES (#HospNum,#IDNum, #DoctorID, #Data, #FileType, 'Patient Photo' , #FileSize, GETDATE())"
End If
reader.Close()
cmd.CommandText = SQLStr
cmd.Parameters.AddWithValue("#HospNum", Session.Item("HospNum"))
cmd.Parameters.AddWithValue("#IDNum", Session.Item("IDNum"))
cmd.Parameters.AddWithValue("#DoctorID", Session.Item("DoctorID"))
cmd.Parameters.AddWithValue("#FileType", lblHeader.Text)
cmd.Parameters.AddWithValue("#FileSize", FileSizeOfIMG.ToString)
cmd.Parameters.Add(ImageTypeDataOfImage)
cmd.ExecuteNonQuery()
con.Close()
GetData()
End Using
End Sub
I haven't figured out what causes this but i have figured out a remedy by having a delete query first then insert data.
SQLStr = "delete FROM [Patient_Data].[dbo].[tbPatientImage] where HospNum='" & Session.Item("HospNum") & "'" & _
" and IDNum='" & Session.Item("IDNum") & "' and FileType= '" & lblHeader.Text & "'"
Dim cmd As New SqlCommand(SQLStr, con)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
SQLStr = " INSERT INTO [Patient_Data].[dbo].[tbPatientImage](HospNum,IDNum, DoctorID, PatImage , FileType, FileName, FileSize , TransDATE) " & _
" VALUES (#HospNum,#IDNum, #DoctorID, #Data, #FileType, 'Patient Photo' , #FileSize, GETDATE())"
cmd.CommandText = SQLStr
'cmd.CommandTimeout = 120
cmd.Parameters.AddWithValue("#HospNum", Session.Item("HospNum"))
cmd.Parameters.AddWithValue("#IDNum", Session.Item("IDNum"))
cmd.Parameters.AddWithValue("#DoctorID", Session.Item("DoctorID"))
cmd.Parameters.AddWithValue("#FileType", lblHeader.Text)
cmd.Parameters.AddWithValue("#FileSize", FileSizeOfIMG)
cmd.Parameters.Add(ImageTypeDataOfImage)
cmd.ExecuteNonQuery()
con.Close()
GetData()
lblMessage.Text = "Saved."
End Using
End Sub

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

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