ASP.NET, VB.NET can't insert data into a SQL Server database - sql

I have been troubleshooting this for a week. I try to insert a value into a SQL Server database. It doesn't show any error but when I check the database, there's no data inserted. I might doing something that is wrong here but I can't find it. Thanks for helping.
Dim connect As New SqlConnection(ConfigurationManager.ConnectionStrings("SqlServer").ToString())
Using coa As New SqlCommand()
With coa
.Connection = connect
.CommandType = CommandType.Text
End With
Try
connect.Open()
Dim insertcmd As String
insertcmd = "insert into tblUserSection (#newValue, #SectionName, #newSectionID) values ," _
& "#newValue, #SectionName, #newSectionID);"
coa.Parameters.Add(New SqlParameter("#newValue", SqlDbType.BigInt))
coa.Parameters("#newValue").Value = newValue
coa.Parameters.Add(New SqlParameter("#SectionName", SqlDbType.NVarChar))
coa.Parameters("#SectionName").Value = SectionName.ToString
coa.Parameters.Add(New SqlParameter("#newSectionID", SqlDbType.BigInt))
coa.Parameters("#newSectionID").Value = newSectionID
coa.ExecuteNonQuery()
connect.Close()
MsgBox("success insert")
Catch ex As Exception
MsgBox("Fail to Save to database")
End Try
End Using

The insert command is incorrect. It has parameters for both the column names and the value; the parameter names should only be used for the values.
Assuming the column names match the parameter names, here's an updated version of the command.
insertcmd = "insert into tblUserSection (newValue, SectionName, newSectionID) values ," _
& "#newValue, #SectionName, #newSectionID);"
The more curious question is why isn't an error showing up. That's because the insert statement is never getting executed. The ExecuteNonQuery command is run against the connection but insertcmd is never associated with the execution in any way.
I'd recommend creating a SQLCommand and using that to execute the query. Here's a sample (and my code might have mistakes, my vb.net is pretty rusty):
Dim sqlcommand as New SqlCommand(coa)
sqlcommand.text = insertcmd
sqlcommand.type = Text
sqlcommand.Parameters.Add(New SqlParameter("#newValue", SqlDbType.BigInt))
sqlcommand.Parameters("#newValue").Value = newValue
sqlcommand.Parameters.Add(New SqlParameter("#SectionName", SqlDbType.NVarChar))
sqlcommand.Parameters("#SectionName").Value = SectionName.ToString
sqlcommand.Parameters.Add(New SqlParameter("#newSectionID", SqlDbType.BigInt))
sqlcommand.Parameters("#newSectionID").Value = newSectionID
sqlcommand.ExecuteNonQuery()

You need to set CommandText property of SqlCommand after creating the insert command string.
like:
Dim connect As New SqlConnection(ConfigurationManager.ConnectionStrings("SqlServer").ToString())
Using coa As New SqlCommand()
With coa
.Connection = connect
.CommandType = CommandType.Text
End With
Try
connect.Open()
Dim insertcmd As String
insertcmd = "insert into [TableName] (newValue, SectionName, newSectionID) values " _
& "(#newValue, #SectionName, #newSectionID);"
coa.CommandText = insertcmd
coa.Parameters.Add(New SqlParameter("#newValue", SqlDbType.BigInt))
coa.Parameters("#newValue").Value = newValue
coa.Parameters.Add(New SqlParameter("#SectionName", SqlDbType.NVarChar))
coa.Parameters("#SectionName").Value = SectionName.ToString()
coa.Parameters.Add(New SqlParameter("#newSectionID", SqlDbType.BigInt))
coa.Parameters("#newSectionID").Value = newSectionID
coa.ExecuteNonQuery()
connect.Close()
MsgBox("success insert")
Catch ex As Exception
MsgBox("Fail to Save to database")
End Try
End Using

Related

Vb.Net 2010 - SQL Insert Command with autonumeric value

I'm looking to add a row with an autonumeric value using SQL.
I'm using Studio VB 2010. I have a very simple table with 2 fields:
ID Autonumeric
Model Text field.
constr = "INSERT INTO procedures VALUES('" & txtFName.Text & "')"
cmd = New OleDbCommand(constr, cn)
cn.Open()
Me.i = cmd.ExecuteNonQuery
A message says a parameter is missing,
so my question is...
How can I add in the SQL command this automatic value? (ID)
Should I get the last ID number and +1 ?? I think there's gotta be a simple way to do it.
Thank you.
Update #1
I am now trying parameterized queries as suggested...
I found this example,
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#a1", OleDbType.Integer).Value = 0
.Add("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
But still, I'm geting a Syntaxis error.
Any thoughts?
Thanks to you all.
UPDATE #2
This code seems to work if I give the next ID number, but again, how can I do it automatically?
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#a1", OleDbType.Integer).Value = 3
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
Any comments? Thanks again.
UPDATE #3 This Code gives me Syntaxis Error
I just put my only one column to update, the second one is the autonumber column, as I was told to try.
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO procedures (procedure) VALUES ('Model')"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
Try
Con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
UPDATE #4 - SOLUTION
I'm putting this code in here in case someone finds it useful.
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;"
dbSource = "Data Source = c:\gastrica\dabase.accdb"
Con.ConnectionString = dbProvider & dbSource
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO [procedures] ([procedure]) VALUES (?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#procedure", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
Dim varProcedure As String = cmd.Parameters("#procedure").Value.ToString()
MessageBox.Show("Record inserted successfully. Procedure = " & varProcedure)
Catch ex As Exception
Throw ex
Finally
Con.Close()
End Try
Thanks all for your comments and help.
You need to specify the columns:
INSERT INTO procedures (columnname, columnname2) VALUES ('test', 'test');
Here is a sql fiddle showing an example:
http://sqlfiddle.com/#!9/3cf706/1
Try this one:
constr = "INSERT INTO procedures (ID, Model) VALUES (0,'" & txtFName.Text & "')"
'or (not sure)
constr = "INSERT INTO procedures (Model) VALUES ('" & txtFName.Text & "')"
When use 0 as value, in autonumeric fields SQL insert the next number
Thanks for your answers.
I couldnĀ“t do it, it gives me errors. So I end up with a single variable reaching the next Auto Value. Using a simple SQL command.
And then, everything runs good.
vNextAuto = GetDB_IntValue("SELECT TOP 1 * FROM procedures ORDER BY ID DESC", "ID") + 1
Dim SQL_command As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#id", OleDbType.Integer).Value = vNextAuto
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
'Dim id As String = cmd.Parameters("#id").Value.ToString()
'MessageBox.Show("Record inserted successfully. ID = " & id)
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try

Update Query Doesn't Work But No Error

(I code VB.NET and use ms access 2016 as database)
I execute this query but nothing happen. I wonder whats wrong. no error when i run it. i debugged it and all the values in the variables are also correct.
no changes happened in my db too
If Not (TextBoxID.Text = "" Or TextBoxNama.Text = "") Then
Try
Dim sqlquery As String = "UPDATE tblEmployees SET Nama = #nama WHERE IDEmployee = #ide"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#ide", TextBoxID.Text)
.Parameters.AddWithValue("#nama", TextBoxNama.Text)
.Connection = FormMain.conn
.ExecuteNonQuery()
End With
ButtonEdit.Text = "EDIT"
ButtonEdit.Image = My.Resources.edit
GroupBox1.Enabled = False
ButtonNew.Enabled = True
Catch ex As Exception
MsgBox(ex.Message)
End Try
Else
MsgBox("Data cannot be empty!")
End If
The problem is that MS Access doesn't have named parameters - but rather positional parameters.
So you must specify the parameters in the correct order in which they appear in your SQL statement. And you're not doing to right now.
Change your code to this:
If Not (TextBoxID.Text = "" Or TextBoxNama.Text = "") Then
Try
Dim sqlquery As String = "UPDATE tblEmployees SET Nama = #nama WHERE IDEmployee = #ide"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#nama", TextBoxNama.Text)
.Parameters.AddWithValue("#ide", TextBoxID.Text)
.Connection = FormMain.conn
.ExecuteNonQuery()
You must set the value for #nama first, before you set the value for #ide, since that's the order in which these parameters appear in your MS Access SQL statement.

Can't INSERT INTO access database

I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.
Code:
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database? I can insert this query by running query directly in Access.
Firstly I would check the database settings. If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one). Rather set it up to COPY IF NEWER.
Further, you should ALWAYS use parameterized queries to protect your data. It is also is less error prone than string concatenated commands ans is much easier to debug.
Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = "
Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
"VALUES " & _
"(#code);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#code", txtCode.Text)
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.Close()
End Using
Here is an example where data operations are in a separate class from form code.
Calling from a form
Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.
Public Class Operations1
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
}
Public Function AddNewRow(
ByVal CompanyName As String,
ByVal ContactName As String,
ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (#CompanyName, #ContactName)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName)
cmd.Parameters.AddWithValue("#ContactName", ContactName)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class

VB.Net Update doesn't update my database

This is the code that I am trying to run. It will run without errors, but it does not update my database.
It will work when it is not Parameterized, but when I add parameters in it starts acting up. Here is the problematic code.
Public Sub updateItem()
Dim sqlConnection1 As New OleDb.OleDbConnection(dbProvider + dbSource)
Dim cmd As New OleDb.OleDbCommand
cmd.CommandText = "Update Inventory set PartNumber='#PartNumber', Brand='#Brand', PartDescription='#PartDescription', PartCost=#PartCost, InventoryOnHand=#InventoryOnHand, PartSupplier='#PartSupplier' where PartNumber = '#PartNumMatch' and Brand = '#PartManMatch';"
cmd.Parameters.AddWithValue("#PartNumber", partNumberText.Text().ToUpper())
cmd.Parameters.AddWithValue("#Brand", ManufacturerText.Text())
cmd.Parameters.AddWithValue("#PartDescription", partDescriptionText.Text())
cmd.Parameters.AddWithValue("#PartCost", Convert.ToDouble(partCostText.Text()))
cmd.Parameters.AddWithValue("#InventoryOnHand", Convert.ToInt32(quantityText.Text()))
cmd.Parameters.AddWithValue("#PartSupplier", partSupplierText.Text())
cmd.Parameters.AddWithValue("#PartNumMatch", partNumberText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#PartManMatch", ManufacturerText.Text().ToUpper().Trim())
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
Try
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
sqlConnection1.Close()
End Try
'SQl statement to try to update the selected row's data matched against the database.
'update listview here.
End Sub
I am almost sure that the syntax is correct because my insert works. Here is the code to my insert.
Private Sub addItem()
'SQL statement here to add the item into the database, if successful, move the information entered to listview.
Dim sqlConnection1 As New OleDb.OleDbConnection(dbProvider + dbSource)
Dim cmd As New OleDb.OleDbCommand
'Dim reader As SqlDataReader
cmd.CommandText = "Insert into Inventory ([PartNumber], [Brand], [PartDescription], [PartCost], [InventoryOnHand], [PartSupplier]) values (#PartNumber, #Brand, #PartDescription, #PartCost, #InventoryOnHand, #PartSupplier);"
cmd.Parameters.AddWithValue("#PartNumber", partNumberText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#Brand", ManufacturerText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#PartDescription", partDescriptionText.Text().Trim())
cmd.Parameters.AddWithValue("#PartCost", partCostText.Text())
cmd.Parameters.AddWithValue("#InventoryOnHand", quantityText.Text())
cmd.Parameters.AddWithValue("#PartSupplier", partSupplierText.Text().Trim())
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
Dim found As Boolean = False
Try
sqlConnection1.Open()
cmd.ExecuteNonQuery()
MessageBox.Show(cmd.CommandText)
sqlConnection1.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
sqlConnection1.Close()
End Try
End Sub
I know that the where clause is right, I have hard-coded the value's and I have also pushed the value's being compared to message box's and compared them directly to the information in the database.
Thanks in advance for any and all opinions and I hope we can get it figured out.
The parameters placeholders should not be enclosed in single quotes
cmd.CommandText = "Update Inventory set PartNumber=#PartNumber, Brand=#Brand, " +
"PartDescription=#PartDescription, PartCost=#PartCost, " +
"InventoryOnHand=#InventoryOnHand, PartSupplier=#PartSupplier " +
"where PartNumber = #PartNumMatch and Brand = #PartManMatch;"
You don't need to do that, it only confuses the code that tries to replace the parameter placeholder with the actual value. They will be treated as literal strings
Try this,
cmd.CommandText = "Update Inventory set PartNumber=#PartNumber, Brand=#Brand, " +
"PartDescription=#PartDescription, PartCost=#PartCost, " +
"InventoryOnHand=#InventoryOnHand, PartSupplier=#PartSupplier " +
"where PartNumber = #PartNumMatch and Brand = #PartManMatch;"
cmd.Parameters.AddWithValue("#PartDescription", partDescriptionText.Text())
cmd.Parameters.AddWithValue("#PartCost", Convert.ToDouble(partCostText.Text()))
cmd.Parameters.AddWithValue("#InventoryOnHand", Convert.ToInt32(quantityText.Text()))
cmd.Parameters.AddWithValue("#PartSupplier", partSupplierText.Text())
cmd.Parameters.AddWithValue("#PartNumMatch", partNumberText.Text().ToUpper().Trim())
cmd.Parameters.AddWithValue("#PartManMatch", ManufacturerText.Text().ToUpper().Trim())

Storing ID from SQL result

Im running the following code to tell if a user excists on a database - standard stuff. Obviously once the code is run a boolean true or false will be returned if there is a result. If a result is found i want to store the ID of the said result. Can anyone tell me how'd id go about doing this?
code:
Username = txtUserName.Text
Password = txtPassword.Text
dbConnInfo = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Dave\Documents\techs.mdb"
con.ConnectionString = dbConnInfo
con.Open()
Sql = "SELECT * FROM techs WHERE userName = '" & Username & "' AND '" & Password & "'"
LoginCommand = New OleDb.OleDbCommand(Sql, con)
CheckResults = LoginCommand.ExecuteReader
RowsFound = CheckResults.HasRows
con.Close()
If RowsFound = True Then
MsgBox("Details found")
TechScreen.Show()
Else
MsgBox("Incorrect details")
End If
There are a lot of problems with the code snippet you posted. Hopefully, I can help you correct these problems.
In order to load the ID of the result you'll want to use SqlCommand.ExecuteScalar() as this is optimized to pull back one result from Sql.
As to what is wrong with your code, you're wide open to Sql Injection attacks and you should be using Parametrized Queries as shown in my sample below.
Public Function AddProductCategory( _
ByVal newName As String, ByVal connString As String) As Integer
Dim newProdID As Int32 = 0
Dim sql As String = _
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); " _
& "SELECT CAST(scope_identity() AS int);"
Using conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar)
cmd.Parameters("#Name").Value = newName
Try
conn.Open()
newProdID = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Return newProdID
End Function
Source: MSDN