'SQL Problem' when trying to update Database in ASP.NET - asp.net

i am currently learning the basics in ASP.NET and now at manipulating Database. It doesn't go to the Try section and straight away head to the Catch ex as Exception part which gives me the message box saying "Unsuccessful Operation or SQL problem.
dgvResult.Visible = True
Try
conn.Open()
dd.Connection = conn
dd.CommandText = "update [STUDENT]" &
"set [Matric]= '" & txtMatric.Text & "', " &
"[Name] ='" & txtName.Text & "'," &
"[Address] ='" & txtAddress.Text & "'," &
"[Telephone] ='" & txtTelephone.Text & "'," &
" where [Matric] ='" & txtMatric.Text & "' "
dd.ExecuteNonQuery()
dd.Dispose()
conn.Close()
MsgBox("Data Updated")
Catch ex As Exception
MsgBox("Unsucessful Operation or SQL Problem")
End Try
End Sub
My task is to edit some information in database and save it.

Related

how can i try and catch duplicate data in the database

Try
con.Open()
comm.Connection = con
comm.CommandText = "insert into [adminanduser] (username,firstname,lastname,email,password,usertype) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & Label6.Text & "')"
comm.ExecuteNonQuery()
Response.Write("Data Successfully Saved")
con.Close()
Catch
Finally
End Try
Unless you alter the table such that there is a unqiue constraint on one of the columns, you will not be able to get an exception when inserting duplicate data. Rather than attempting to generate an error though, you could always use SQL to ensure that a duplicate entry won't be added. Presuming you are trying to keep unique usernames, you could always write your SQL like this:
comm.CommandText = #"IF NOT EXISTS(SELECT * FROM [adminanduser] WHERE [username] = #username)
INSERT INTO [adminanduser] SELECT #username,#firstname,#lastname,#email,#password,#usertype";
comm.Parameters.AddWithValue("#username", TextBox1.Text);
comm.Parameters.AddWithValue("#firstname", TextBox2.Text);
comm.Parameters.AddWithValue("#lastname", TextBox3.Text);
comm.Parameters.AddWithValue("#email", TextBox4.Text);
comm.Parameters.AddWithValue("#password", TextBox5.Text);
comm.Parameters.AddWithValue("#usertype", TextBox6.Text);
If you would rather go down the road of generating the error, try
ALTER TABLE [adminanduser]
ADD UNIQUE (username)
That should throw an exception the next time you attempt to insert a duplicate username

insert into syntax error

Private databaseConnector As DatabaseConnector
Dim fulltxtSQL As String
DatabaseConnector = New DatabaseConnector
Try
fulltxtSQL = "insert into [user-table] (username, password) VALUES ('" & UserName.Text & "','" & Password.Text & "')"
DatabaseConnector.RunSqlNonQuery(fulltxtSQL)
If DatabaseConnector.RunSqlNonQuery(fulltxtSQL) = True Then
MsgBox("thank you for registering ", vbInformation, Title.Trim)
Response.Redirect("Default.aspx")
Exit Sub
Else
MsgBox(MsgBox("There has been a error in your registering", vbInformation, Title.Trim))
End If
Catch ex As Exception
MsgBox(ex.Message.Trim, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Me.Title.Trim)
Exit Sub
End Try
End Sub
am trying to get the data from textbox to the database table.
syntax error in insert into statement the connection to the database works fine but when it reaches the insert into statement i get the error
Try this
INSERT INTO [user-table] ([username],[password]) VALUES('" & UserName.Text & "','" & Password.Text & "')"
You query contains special character such as user,table and password so it will give error. So what you need to do is to put such characters in paranthesis [].
Also you should use parameterized query.
try using this command
cmd = New System.Data.OleDb.OleDbCommand("INSERT INTO [user-table] ([username],[password]) VALUES('" & UserName.Text & "','" & Password.Text & "')", con)
if your table name contains such special charaters then use square brackets.

Incorrect syntax near the keyword 'close'

I have a section of code in one of my scripts that is getting an error in its syntax.
if(status <> true and Request.QueryString("selectId") = "undefined") then
strConn ="PROVIDER=foobar;Server=foo;Database=foo;Uid=bar;Pwd=bar;"
Set cnt = Server.CreateObject("ADODB.Connection")
set rs1 = CreateObject("ADODB.Recordset")
rs1.CursorLocation = adUseClient
cnt.ConnectionString= strConn
cnt.Open strConn
sql="Select * from rule1 where skucode='" & Request.Form("txthidden") & "' and letter1id ='" & Request.Form("lrt1") & "' and letter2id ='" & Request.Form("Select1") & "' and letter3id ='" & Request.Form("Select2") & "'"
rs1.Open sql,cnt,2,2
if not rs1.EOF then
Response.write("<script language=""javascript"">alert('Rules already exists!');</script>")
else
sql="INSERT INTO rule1 (letter1id,letter2id,letter3id,HTML,skucode) VALUES "
sql=sql & "('" & Request.Form("lrt1") & "',"
sql=sql & "'" & Request.Form("Select1") & "',"
sql=sql & "'" & Request.Form("Select2") & "',"
sql=sql & "'" & Request.Form("txthtml") & "',"
sql=sql & "'" & Request.Form("txthidden") & "')"
cnt.Execute sql
Response.write("<script language=""javascript"">alert('Rules Added successfully!');window.location='" & "viewrule1.asp?skucodes=" & Request.Form("txthidden") & "';</script>")
end if
rs1.Close
cnt.close
The error message I get is:
Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near the keyword 'close'.
/path/file.asp, line 75
Instead of closing it, you can detach it completely:
set cnt = Nothing
There shouldn't be a problem. All i think is if your data is too long or not. Sometimes it occurs when your row limit exceeds. SQL Server 6.5 allows a maximum row size of 1962 bytes and SQL Server 7.0 allows a maximum row size of 8060 bytes. Its just an assumption
Presuming it's the last line that's throwing the error, I'd replace it with:
If IsObject(cnt) Then
On Error Resume Next
If cnt.State = 1 Then ' 1 = adStateOpen '
cnt.Close
End If
Set cnt = Nothing
Err.Clear
On Error Goto 0
End If
cnt is probably already closed by the time it reaches that portion of your script which is why it's throwing the error. Checking its status before closing it needs to be wrapped in On Error Resume Next logic, otherwise it'll throw another error.

sql subquery syntax asp.net

I am trying to excute this sql query
Dim str As String = "UPDATE table1 SET " & _
"number = '" & strc & "'," & _
"code = '" & "123" & "'," & _
"line= '" & dd1.text & "'," & _
"sellr = '" & txtrun.text & "'," & _
"endu= '" & txtex1.value+txtex2.value & "'" & _
"WHERE number IN (select table1.number" & _
"FROM table1 INNER JOIN table2 ON table1.number = table2.number" & _
"WHERE ((table1.username)='" & session("username") & "' AND (table1.pass)='" & session("pass") & "' AND (table2.sellnum)='" & session("sellnum") & "'));"
there is a Syntax error in query expression and this is te first time I am using nested subquery
all the field are getting String values
So if someone can tell me what is the right approach to write this query I will be very grateful
You're missing spaces after table1.number and table2.number fields in the subquery.
I don't know where you're using this query, but you might want to read about SQL injection. When you stick strings together to build SQL, your code may be vulnerable to malicious users who put SQL code into the fields of your application.

Excepted end of statement error in ASP

When inserting data into a database, the following error occurs
"Excepted end of statement"
sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) VALUES ('" & Email & "', '" & First Name & "','" & Last Name & "','" & Comments & "')"
objConn.Execute sqlstr
Try using single-word identifiers for your first-name and last-name variables:
sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) " & _
" VALUES ('" & Email & "', '" & FirstName & "','" & LastName & "','" & Comments & "')"
objConn.Execute sqlstr
Assuming you've got variables with those names in your VBScript, that'll solve your current problem with Expected end of statement.
Your second problem is your code's vulnerability to SQL injection.
To help fix that problem, see:
Classic ASP SQL Injection Protection
http://www.stardeveloper.com/articles/display.html?article=2008112501&page=1
You might have single quote in one of the values, resulting in invalid SQL. You have to escape single quotes, though better rewrite your code to use parameters instead.
sqlstr = "INSERT INTO tblContact (Email, FirstName, LastName, Comments) " & _
" VALUES ('" & Replace(Email, "'", "''") & "', '" & Replace(FirstName, "'", "''") & "', '" & Replace(LastName, "'", "''") & "', '" & Replace(Comments, "'", "''") & "')"
objConn.Execute sqlstr

Resources