I have 4 tables: Code_Product, Name_Product, Color_Product, Size_Product
And code:
Public Sub ExecuteQuery(query As String)
Dim command As New SqlCommand(query, connection)
command.ExecuteNonQuery()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' , Color_Product = '" & txtColorProduct.Text & "', Size_Product = '" & txtSizeProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
ExecuteQuery(updateQuery)
MessageBox.Show("Data has been changed")
Notes: the code work.
But, the code changes all columns, and I just want to change only one column. How?
replace this line
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' , Color_Product = '" & txtColorProduct.Text & "', Size_Product = '" & txtSizeProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
with this. Pass only that column which you want to update.
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
Related
Here's my code:
strSQL = "UPDATE tblTransactions SET Verifier = '" & strUserName & "' WHERE PatientAccountNumber = '" & Me.PatientAccountNumber & "'"
strSQL = "UPDATE tblTransactions SET VerifierAssgnDate = #" & Date & "# WHERE PatientAccountNumber = '" & Me.PatientAccountNumber & "'"
"Verifier" updates fine, but "VerifierAssignDate" throws a "field not updateable" error. It's a DateTime field.
Thanks!
You can and should combine these (and VerifierAssgnDate was probably misspelled):
strSQL = "UPDATE tblTransactions " & _
"SET Verifier = '" & strUserName & "', VerifierAssignDate = Date() " & _
"WHERE PatientAccountNumber = '" & Me.PatientAccountNumber & "'"
Im getting a Data type mismatch in criteria expression.
This is an update button Im trying to implement.
Access_Num is the only number(data_type) here.
I'm using MSACCESS2007
Is it a good pracrice to make all data types in the database as text?
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
cn = New OleDbConnection(con)
cn.Open()
With cmd
.Connection = cn
.CommandText = "Update [Book] SET [Book_ID] = '" & TextBox1.Text & _
"', [Access_Num] = '" &Integer.Parse(TextBox2.Text) & _
"', [Title] = '" & TextBox3.Text & _
"', [Author] = '" & TextBox4.Text & _
"', [Publisher] = '" & TextBox5.Text & _
"', [Category] = '" & ComboBox1.Text & _
"', [Contents] = '" & TextBox7.Text & _
"', [Availability] = '" & ComboBox2.Text & "' WHERE [Access_Num] = '" & Integer.Parse(TextBox2.Text) & "'"
.ExecuteNonQuery()
End With
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'cn.Close()
'cmd.Dispose()
MsgBox("Successfully Updated")
End Sub
Your problem is that you have string delimiters everywhere. Remove them for all fields that aren't strings:
With cmd
.Connection = cn
.CommandText = "Update [Book] SET [Book_ID] = '" & TextBox1.Text & _
"', [Access_Num] = " & Integer.Parse(TextBox2.Text) & _
", [Title] = '" & TextBox3.Text & _
"', [Author] = '" & TextBox4.Text & _
"', [Publisher] = '" & TextBox5.Text & _
"', [Category] = '" & ComboBox1.Text & _
"', [Contents] = '" & TextBox7.Text & _
"', [Availability] = '" & ComboBox2.Text & "' WHERE [Access_Num] = " & Integer.Parse(TextBox2.Text)
.ExecuteNonQuery()
End With
Note that a better way would be to use parameters for the query, since that also avoids SQL injection.
Is it a good pracrice to make all data types in the database as text?
No, certainly not! That's an awful practice. Data types should represent the data stored in the column, and be the smallest practical type to represent that data.
I need help figuring out why I'm getting this syntax error when trying to run this code in Microsoft Access. I am working on this database for work and have some experience with it, but not a whole lot.
I created a database before the one I'm currently working on and it works fine. It is very similar to the database that I'm working on now, so I just copied it and then renamed the fields and text boxes and everything to match the information that this database will be handling.
Essentially I have a table with the data and then I want a form that has a text box for each field in the table with a subtable of the main table incorporated into the form. The user fills in the text boxes with the information and then either adds it to the table or they can click on a record and edit it or delete it with the corresponding buttons on the form.
Now I'm getting a runtime error '3134': syntax error in INSERT INTO statement when trying to click the add button on one of my forms. This only happens on the add button and consequently the update button if it is set to update, but all of the other buttons work fine.
Here is the code for the new database:
Option Compare Database
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtICN.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO tblInventory(ICN, manu, model, serial, desc, dateRec, dateRem, dispo, project, AMCA, UL, comments) " & _
" VALUES(" & Me.txtICN & ", '" & Me.txtManu & "', '" & Me.txtModel & "', '" & Me.txtSerial & "', '" & Me.txtDesc & "', '" & Me.txtDateRec & "', '" & Me.txtDateRem & "', '" & Me.txtDispo & "', '" & Me.txtProject & "', '" & Me.txtAMCA & "', '" & Me.txtUL & "', '" & Me.txtComments & "')"
Else
'otherwise (Tag of txtICN store the ICN of item to be modified)
CurrentDb.Execute "UPDATE tblInventory " & _
" SET ICN = " & Me.txtICN & _
", manu = '" & Me.txtManu & "'" & _
", model = '" & Me.txtModel & "'" & _
", serial = '" & Me.txtSerial & "'" & _
", desc = '" & Me.txtDesc & "'" & _
", dateRec = '" & Me.txtDateRec & "'" & _
", dateRem = '" & Me.txtDateRem & "'" & _
", dispo = '" & Me.txtDispo & "'" & _
", project = '" & Me.txtProject & "'" & _
", AMCA = '" & Me.txtAMCA & "'" & _
", UL = '" & Me.txtUL & "'" & _
", comments = '" & Me.txtComments & "'" & _
" WHERE ICN = " & Me.txtICN.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
frmInventorySub.Form.Requery
End Sub
Private Sub cmdClear_Click()
Me.txtICN = ""
Me.txtManu = ""
Me.txtModel = ""
Me.txtSerial = ""
Me.txtDesc = ""
Me.txtDateRec = ""
Me.txtDateRem = ""
Me.txtDispo = ""
Me.txtProject = ""
Me.txtAMCA = ""
Me.txtUL = ""
Me.txtComments = ""
'focus on ID text box
Me.txtICN.SetFocus
'set button edit to enable
Me.cmdEdit.Enabled = True
'change caption of button add to Add
Me.cmdAdd.Caption = "Add"
'clear tag on txtICN for reset new
Me.txtICN.Tag = ""
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Private Sub cmdDelete_Click()
'delete record
'check existing selected record
If Not (Me.frmInventorySub.Form.Recordset.EOF And Me.frmInventorySub.Form.Recordset.BOF) Then
'confirm delete
If MsgBox("Are you sure you want to delete this item?", vbYesNo) = vbYes Then
'delete now
CurrentDb.Execute "DELETE FROM tblInventory " & _
"WHERE ICN =" & Me.frmInventorySub.Form.Recordset.Fields("ICN")
'refresh data in list
Me.frmInventorySub.Form.Requery
End If
End If
End Sub
Private Sub cmdEdit_Click()
'check whether there exists data in list
If Not (Me.frmInventorySub.Form.Recordset.EOF And Me.frmInventorySub.Form.Recordset.BOF) Then
'get data to text box control
With Me.frmInventorySub.Form.Recordset
Me.txtICN = .Fields("ICN")
Me.txtManu = .Fields("manu")
Me.txtModel = .Fields("model")
Me.txtSerial = .Fields("serial")
Me.txtDesc = .Fields("desc")
Me.txtDateRec = .Fields("dateRec")
Me.txtDateRem = .Fields("dateRem")
Me.txtDispo = .Fields("dispo")
Me.txtProject = .Fields("project")
Me.txtAMCA = .Fields("AMCA")
Me.txtUL = .Fields("UL")
Me.txtComments = .Fields("comments")
'store id of item in Tag of txtICN in case ICN is modified
Me.txtICN.Tag = .Fields("ICN")
'change caption of button add to Update
Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
And here is the code for the old database:
Option Compare Database
Private Sub cmdAdd_Click()
'when we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtID.Tag & "" = "" Then
'this is for insert new
'add data to table
CurrentDb.Execute "INSERT INTO tblEquipmentList(equipID, equipDesc, equipManu, equipModelNum, equipSerNum, lastCalDate, calDue) " & _
" VALUES(" & Me.txtID & ", '" & Me.txtDesc & "', '" & Me.txtManu & "', '" & Me.txtModelNum & "', '" & Me.txtSerNum & "', '" & Me.txtLastCalDate & "', '" & Me.txtCalDueDate & "')"
Else
'otherwise (Tag of txtID store the id of equipment to be modified)
CurrentDb.Execute "UPDATE tblEquipmentList " & _
" SET equipID = " & Me.txtID & _
", equipDesc = '" & Me.txtDesc & "'" & _
", equipManu = '" & Me.txtManu & "'" & _
", equipModelNum = '" & Me.txtModelNum & "'" & _
", equipSerNum = '" & Me.txtSerNum & "'" & _
", lastCalDate = '" & Me.txtLastCalDate & "'" & _
", calDue = '" & Me.txtCalDueDate & "'" & _
" WHERE equipID = " & Me.txtID.Tag
End If
'clear form
cmdClear_Click
'refresh data in list on form
frmEquipmentListSub.Form.Requery
End Sub
Private Sub cmdClear_Click()
Me.txtID = ""
Me.txtDesc = ""
Me.txtManu = ""
Me.txtModelNum = ""
Me.txtSerNum = ""
Me.txtLastCalDate = ""
Me.txtCalDueDate = ""
'focus on ID text box
Me.txtID.SetFocus
'set button edit to enable
Me.cmdEdit.Enabled = True
'change caption of button add to Add
Me.cmdAdd.Caption = "Add"
'clear tag on txtID for reset new
Me.txtID.Tag = ""
End Sub
Private Sub cmdClose_Click()
DoCmd.Close
End Sub
Private Sub cmdDelete_Click()
'delete record
'check existing selected record
If Not (Me.frmEquipmentListSub.Form.Recordset.EOF And Me.frmEquipmentListSub.Form.Recordset.BOF) Then
'confirm delete
If MsgBox("Are you sure you want to delete this piece of equipment?", vbYesNo) = vbYes Then
'delete now
CurrentDb.Execute "DELETE FROM tblEquipmentList " & _
"WHERE equipID =" & Me.frmEquipmentListSub.Form.Recordset.Fields("equipID")
'refresh data in list
Me.frmEquipmentListSub.Form.Requery
End If
End If
End Sub
Private Sub cmdEdit_Click()
'check whether there exists data in list
If Not (Me.frmEquipmentListSub.Form.Recordset.EOF And Me.frmEquipmentListSub.Form.Recordset.BOF) Then
'get data to text box control
With Me.frmEquipmentListSub.Form.Recordset
Me.txtID = .Fields("equipID")
Me.txtDesc = .Fields("equipDesc")
Me.txtManu = .Fields("equipManu")
Me.txtModelNum = .Fields("equipModelNum")
Me.txtSerNum = .Fields("equipSerNum")
Me.txtLastCalDate = .Fields("lastCalDate")
Me.txtCalDueDate = .Fields("calDue")
'store id of equipment in Tag of txtID in case id is modified
Me.txtID.Tag = .Fields("equipID")
'change caption of button add to Update
Me.cmdAdd.Caption = "Update"
'disable button edit
Me.cmdEdit.Enabled = False
End With
End If
End Sub
As you can see, I'm pretty confident that they're pretty much identical except for the field names.
I'm also linking an album of screenshots of the database here: http://imgur.com/a/xLV3Q
Thanks for any help you guys can provide.
The problem may be:
Your new table tblInventory has a column DESC which is a SQL reserved keyword. You have two options:
Drop the column DESC and create a new column with different name OR;
Add brackets to your script like this: INSERT INTO tblInventory([ICN], [manu], [model], [serial], [desc], [dateRec], [dateRem], [dispo], [project], [AMCA], [UL], [comments]).
Please check a full list of SQL reserved keywords: Reserved Keywords-Transact-SQL
I have an Excel workbook with the below code -
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sFirstName, sLastName As String
With Sheets("Sheet1")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;" & _
"Data Source=server1;" & _
"Initial Catalog=table1;" & _
"User ID=user1; Password=pass1"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sFirstName = .Cells(iRowNo, 1)
sLastName = .Cells(iRowNo, 2)
'Generate and execute sql statement
' to import the excel rows to SQL Server table
conn.Execute "Insert into dbo.Customers (FirstName, LastName) " & _
"values ('" & sFirstName & "', '" & sLastName & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
End Sub
This opens up a connection to my database and inputs the values from the stated columns.
The primary key is an incremental key on the database. The problem is it will copy ALL values.
I'd like to add new rows of data into the Excel Sheet and only insert those rows that don't already exist.
I've tried different methods ('merge', 'if exist', if not exist', etc.) but I can't get it right.
The solution has to be through VBA. Setting up a link using SSMS is not an option.
I understand that it may be possible to use temporary tables and then trigger a procedure which performs the merge but I want to look into that as a last resort. Haven't read up on it yet (making my way through my MS SQL bible book) but I'm hoping it won't be necessary.
---Update from #Kannan's answer---
New portion of VBA -
conn.Execute "IF EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _
"THEN UPDATE dbo.customers SET WHERE Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' " & _
"ELSE INSERT INTO dbo.Customers (FirstName, LastName) " & _
"VALUES ('" & sFirstName & "', '" & sLastName & "')"
This returns error 'Incorrect syntax near the keyword 'THEN'.
Your SQL query isn't quite right - there is no THEN in a SQL IF.
Also, you don't need to do anything if it does exist, so just use if not exists.
"IF NOT EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _
"INSERT INTO dbo.Customers (FirstName, LastName) " & _
"VALUES ('" & sFirstName & "', '" & sLastName & "')"
This should do it for you.
Sub Button_Click()
'TRUSTED CONNECTION
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim strFirstName, strLastName As String
Dim server, username, password, table, database As String
With Sheets("Sheet1")
server = .TextBox1.Text
table = .TextBox4.Text
database = .TextBox5.Text
If con.State <> 1 Then
con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
'con.Open
End If
'this is the TRUSTED connection string
Set rs.ActiveConnection = con
'delete all records first if checkbox checked
If .CheckBox1 Then
con.Execute "delete from tbl_demo"
End If
'set first row with records to import
'you could also just loop thru a range if you want.
intImportRow = 10
Do Until .Cells(intImportRow, 1) = ""
strFirstName = .Cells(intImportRow, 1)
strLastName = .Cells(intImportRow, 2)
'insert row into database
con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
intImportRow = intImportRow + 1
Loop
MsgBox "Done importing", vbInformation
con.Close
Set con = Nothing
End With
Exit Sub
errH:
MsgBox Err.Description
End Sub
Add a reference to:
Microsoft ActiveX Data Objects 2.8 Library
FYI, my sheet looks like this.
You can use sql query like this:
IF Exists ( Select 1 from dbo.customers where Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' THEN Update dbo.customers set --other columns where Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "'
ELSE Insert into dbo.Customers (FirstName, LastName) " & _
"values ('" & sFirstName & "', '" & sLastName & "')"
Not sure about the syntax for excel and C#, you can correct that similar to this query
I want to add data to my App table in Visual Studio. When I run the program, I fill the information into the text boxes, and when I click the add button, I receive this message from this code:
"Cmd.ExecuteNONQuerry" : An unhandled exception of type
'System.Data.SqlClient.SqlException' occurred in System.Data.dll
When I run "Build Solution" I receive this:
========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
Can somebody please help me.
Imports System.Data.SqlClient
Public Class APP
Dim Con As New SqlConnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
Con.Open()
Dim Cmd As New SqlCommand(("INSERT INTO App VALUES('" & _
ID.Text & "','" & _
Dat.Text & "','" & _
Inst.Text & "', '" & _
Credent.Text & "', '" & _
AppOwner.Text & "', '" & _
Status.Text & "', '" & _
SerialNr.Text & "', '" & _
MAC.Text & "', '" & _
DellNr.Text & "', '" & _
Model.Text & "', '" & _
Description.Text & _
"', '" & Service.Text & _
"', '" & Indkøbt.Text & "',)"), Con)
Cmd.ExecuteNonQuery()
Con.Close()
MsgBox("Success....", MsgBoxStyle.Information, "SUCCESS")
ID.Clear()
Dat.Clear()
Inst.Clear()
Credent.Clear()
AppOwner.Clear()
Status.Clear()
SerialNr.Clear()
MAC.Clear()
DellNr.Clear()
Model.Clear()
Description.Clear()
Service.Clear()
Indkøbt.Clear()
ID.Focus()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Con.ConnectionString = "Data Source=BYG-A101-MOELKA;Initial Catalog=App;Integrated Security=True"
End Sub
At the first glance:
"', '" & Indkøbt.Text & "',)"), Con)
is wrong, it should be
"', '" & Indkøbt.Text & "')"), Con)
But there is another big Problem: you are not using sqlparameters, so your code will crash if someone enters a "'".
When using an insert like you do, it´s also ... more readable if you also specify the field list to see, if you inserting values in the correct databasefield. But much better change to sqlparameters.
Addition - SQL Parameters (with an update Statement, but the principle should be clear):
sqlStmt = "UPDATE table SET fieldname = #fieldparameter WHERE ..."
Using sqlComm As New SqlCommand(sqlStmt, sqlConn)
sqlComm.Parameters.Add(New SqlParameter("#fieldparameter", yourvalue))
sqlComm.ExecuteNonQuery()
End Using