How to Insert a query into two diff table vb.net - mysql

I'm having trouble inserting an item from two different tables using a vb.net and MySql
This is Item table and Stocks Table in a single query:
Dim rsitem As New ADODB.Recordset
rsitem.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rsitem.CursorType = ADODB.CursorTypeEnum.adOpenDynamic
rsitem.Open("Insert Into items,stocks itemno = '" & txtItemNo.Text & "', Description = '" & txtDescription.Text & "', Price = '" & txtPrice.Text & "', Brand = '" & txtBrand.Text & "', stocks_on_hand = '" & txtStocks.text &"'",cn)
My problem is when I type in inputbox the txtStocks.text doesn't show what I input from my vb.net into mysql db. I think I have a wrong query. Can someone help me. ?

Firstly you need to make sure that the textboxes are not empty
Then concerning your rsitem.Open, I saw you Open it twice.
Thirdly, your query is wrong! whats the name of your Table you wish to insert into? I guess it's items?
You can try the following;
If not (String.IsNullOrEmpty(txtItemNo.Text) Orelse String.IsNullOrEmpty(txtDescription.Text) Orelse _
String.IsNullOrEmpty(txtPrice.Text) Orelse String.IsNullOrEmpty(txtBrand.Text) Orelse _
String.IsNullOrEmpty(txtStocks.Text) Then
rsitem.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rsitem.CursorType = ADODB.CursorTypeEnum.adOpenDynamic
rsitem.Open(String.format( _
"Insert Into items (itemno, Description, Price, Brand, stocks_on_hand) values ('{0}','{1}','{2}','{3}','{4}') ", _
txtItemNo.Text, txtDescription.Text, txtPrice.Text, txtBrand.Text, txtStocks.text), connection)
End If

Related

Insert a value into a table while creating a record in another table

I'm out of my league on this... Another developer before me did something similar to what I want to do by adding a value in a table while updating another table. However, he was running updates as well as inserting, and his primary key was text. Mine PK is integer. Here's his code (works great) that I am trying to reverse engineer and apply to my situation:
Dim sqlQuery As String
sqlQuery = "IF EXISTS (SELECT ReportPK FROM
ACIST_MobilePipelineReportReviewed WHERE ReportPK = '" & ReportPk & "') " &
_
" UPDATE ACIST_MobilePipelineReportReviewed set Status = 'Approved'
WHERE ReportPK = '" & ReportPk & "'" & _
" ELSE " & _
" INSERT INTO ACIST_MobilePipelineReportReviewed ([ReportPK],
[PipelineUID],[ReportDate],[ReportInspector],[Status]) VALUES (" & _
"'" & ReportPk & "','" & Me!PipelineUID & "','" & Me!ReportDate & "','"
& Me!ReportInspector & "','Approved')"
End Sub
Here's what I'm doing: I have a combo box on a form called FacilityEntryF. That form is tied to my FacilityT table. I am selecting "CampaignID" from the CampaignT table and adding it to the FacilityT using that combo box in the aforementioned form. No biggie there... Works great.
The FacilityT has many columns of which I have [FacilityID] which is the primary key and is an autogenerated integer. It also has a column for [CampaignID] which is a foreign key from the CampaignT table.
After adding the CampaignID and starting a new FacilityID in FacilityT, I also want to create a new record in my CampaignFacilityParticipationT table. That table consists of only three columns: CampaignFacilityParticipationID, CampaignID, ParticipantFacilityID. I want to take the new [FacilityID] and the [CampaignID] I added to that table and insert them into the CampaignFacilityParticipationT table (FacilityID goes into the ParticipantFacilityID column). Here's the code below that didn't work (which I'm not surprised because I don't know what I'm doing):
Dim sqlQuery As String
sqlQuery = "IF EXISTS (SELECT FacilityID FROM FacilityT WHERE FacilityID =
" & FacilityID) " & _
" INSERT INTO CampaignFacilityParticipationT ([CampaignFacilityParticipationID],[CampaignID],[ParticipantFacilityID]) VALUES (" & _
"" & CampaignFacilityParticipationID,'" & Me!CampaignID," & Me!ParticipantFacilityID, CampaignID)"
End Sub
Using MS Access 2013 with Microsoft SQL backend.
Thanks!!!
Concatenation is not correct. If apostrophes are needed to delimit parameters then make sure they are used consistently. Normally in Access, apostrophes would only be used for text fields, # for date/time and nothing for number. Maybe because backend is MS SQL apostrophes are needed for all field types? Why do you repeat CampaignID in VALUES clause?
sqlQuery = "IF EXISTS (SELECT FacilityID FROM FacilityT WHERE FacilityID = '" & Me!FacilityID & "')" & _
" INSERT INTO CampaignFacilityParticipationT ([CampaignFacilityParticipationID],[CampaignID],[ParticipantFacilityID])" & _
" VALUES ('" & Me!CampaignFacilityParticipationID & "','" & Me!CampaignID & "','" & Me!ParticipantFacilityID & "')"
Is it possible for you to use a subform on FacilityEntryF on which you select the CampaignID? That will eliminate the need for this code.

CheckIfExist. If exist don't insert the data, if not insert the data

I have a problem on how to insert data into two different table. So my requirements is this.
Under Group Details, The user need to click all the needed information on the dropdown menu and input on the textbox of the table grid view before clicking the ADD Link, after this the page will load displaying the Added Job Title and business group details. The user is allowed to input as many Job title as the user want.
I already finished the table but I have problems in saving the data that I input.
So my first table looks like this Before
and I edit it and this is my table Now
So my problem is this, in my database i have two table. One is EMPGROUP_TBL with columns SEQID, masterID, Business Unit, Division, Sub-Division etc. and the other is EMP_MASTERTBL with columns MasterID, Name, LastName, Jobtitle.
Now everytime I click Add link the jobtitle will not be able to save in the EMP_MASTERTBL so I create a code in VB.Net that will update the EMP_MASTERTBL table when I click the add button under Group Details.
Here's my codes.
If UpdateInsDelRecord("INSERT INTO EMPGROUP_TBL (MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & Me.ddl_BusinessUnit.SelectedValue.ToString() & "' ," & _
"'" & val_division & "' ," & _
"'" & val_subdivision & "' ," & _
"'" & Me.ddl_Classification.SelectedValue.ToString() & "' ," & _
"'" & Me.ddl_SubClassification.SelectedValue.ToString() & "')" & _
";" & _
"UPDATE EMP_MASTERTBL SET JOBTITLE = '" & Me.txtJobtitle.Text & "' " & _
"WHERE MASTERID = '" & Me.lblval_Empid.Text & "'") = True Then
Return True
Response.Redirect("eHR_EmpMaintenance.aspx")
Else
Return False
End If
But the user must be able to add as many as Jobtitle and EMPGROUP_TBL details as the user want. So I'm thinking that I'll just write another query for that? How can I add the Group Details and be able to add as many as Jobtitle as the user want?
CheckIfExist
I figured maybe I could use the CheckIfExist and if the employee has an existing data to the jobtitle, business unit, division, sub-division, classification and sub-classification similar to the one that you will add, the messagebox will show that the data already exist. If no data found then it will be able to add the details under the employee's group details. And if you input similar jobtitle but different business unit etc. the data will just be updated and vice versa.
Here's what my code for this.
Function SaveUserGroup() As Boolean
Try
Dim jobtitle As String = Me.txtJobtitle.Text
Dim businessunit As String = Me.ddl_BusinessUnit.SelectedValue
Dim division As String = Me.ddl_Division.SelectedValue
Dim subdivision As String = Me.ddl_SubDivision.SelectedValue
Dim classification As String = Me.ddl_Classification.SelectedValue
Dim subclassification As String = Me.ddl_SubClassification.SelectedValue
Dim CheckMasterTblIfExist As Boolean
Dim CheckGroupTblIfExist As Boolean
Dim insrtResult As Boolean
Dim seqid As String = Me.lblSEQID.Text
Dim emp_id As String = Request.QueryString("emp_id")
If jobtitle <> "" And businessunit <> "Please Select" And division <> "Please Select" And subdivision <> "Please Select" And classification <> "Please Select" And subclassification <> "Please Select" Then
CheckMasterTblIfExist = CheckRecord("SELECT MASTERID, JOBTITLE FROM EMP_MASTERTBL WHERE JOBTITLE = '" & jobtitle & "' AND MASTERID = '" & emp_id & "' ")
CheckGroupTblIfExist = CheckRecord("SELECT * FROM EMPGROUP_TBL WHERE BUSINESS_UNIT = '" & businessunit & "' AND DIVISION = '" & division & "' AND SUB_DIVISION = '" & subdivision & "' AND CLASSIFICATION = '" & classification & "' AND SUB_CLASSIFICATION = '" & subclassification & "' AND MASTERID = '" & emp_id & "' AND SEQID = '" & seqid & "'")
If Not CheckMasterTblIfExist And CheckGroupTblIfExist Then
insrtResult = UpdateInsDelRecord("UPDATE EMP_MASTERTBL SET JOBTITLE = '" & jobtitle & "' " & _
"WHERE MASTERID = '" + Me.lblval_Empid.Text + "'" & _
";" & _
"INSERT INTO EMPGROUP_TBL(MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & businessunit & "' ," & _
"'" & division & "' ," & _
"'" & subdivision & "' ," & _
"'" & classification & "' ," & _
"'" & subclassification & "')")
If Not insrtResult Then
MessageBox("alert('Error Ocurred While Inserting a Data.')")
Else
MessageBox("alert('Successfully Added.')")
End If
Else
MessageBox("alert('Data Already Exist.')")
End If
End If
Catch ex As Exception
MessageBox("Error Ocurred while Inserting a data")
Throw
End Try
End Function
I haven't been completed the code yet. I'm in the adding if there's no data and my problem is that the messagebox keeps on telling me that the data already exist even if there's still no employee's group details that added. Please help me with this.
begin tran
if exists (select * from table with (updlock,serializable) where key = #key)
begin
update table set ...
where key = #key
end
else
begin
insert into table (key, ...)
values (#key, ...)
end
commit tran
you can use like this

How do I update MySQL from visual studio 2010?

I need to update a MySQL database with the new values just collected.
The program will get values like this:
sql = "select * from Accounts where username ='" & txtuname.Text & "' and userpassword = '" & txtpass.Text & "'"
Dim credits As String
credits = publictable.Rows(0).Item(5)
credit.Text = "" & credits
Then it will update the current value with a new value like this:
cmd.CommandText = "UPDATE * Accounts SET credits = '& credit.Text + 10 &' WHERE username = '& Form1.txtuname.Text & '"
However, I am stuck on the UPDATE string.
I think, you have to study well about the update command, since your query syntax is wrong. and you are making some syntactical mistake in the formation of the query. use Line continuation operators to make the query more understandable. plan the output before you query.
cmd.CommandText = "UPDATE Accounts SET " & _
"credits = '" & val(credit.Text) + 10 & "'" & _
"WHERE username = '" & Form1.txtuname.Text & '"

Adding values into a table with a query

So all I'd like to do is add two queries into a table called tmpGroupSearch. I'm not sure how to do it wit out creating a record set and looping through every record and individually adding them in. I'm thinking there is a much easier way to do this I just can't find the proper structure.
Here are my queries:
"SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
"Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
You can follow an INSERT INTO clause with a list of values, like #Asad shows, or also a SELECT query. Do yourself a favor and always list the field names in your SQL or you are just creating time bombs for the future.
Dim strSelect1 As String
Dim strSelect2 As String
strSelect1 = "SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
strSelect2 = "Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
Dim strInsert1 As String
Dim strInsert2 As String
strInsert1 = "INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown) " & strSelect1
'the next version is valid SQL, but *dangerous* because field names are not enumerated
strInsert2 = "INSERT INTO tmpGroupSearch " & strSelect2
It is possible to write the INSERT INTO statement in two forms.
The first form does not specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Test this parameter query in the Access query designer and adjust as needed so that it returns the row set you expect for the pSearchText parameter value you supply.
PARAMETERS pSearchText Text ( 255 );
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
FROM
tblGroupHeader AS gh
LEFT JOIN tblAlsoKnown AS ak
ON gh.GroupNum = ak.GroupNum
WHERE
gh.GroupName Like "'" & pSearchText & "*'"
OR gh.GroupNum Like "'" & pSearchText & "*'"
UNION ALL
SELECT al.GroupName, al.GroupNum, al.AlsoKnown
FROM tblActionLog AS al
WHERE al.AlsoKnown Like "'" & pSearchText & "*'"
Once you have it returning the correct data, convert it to an INSERT query by changing the beginning of the statement to this ...
PARAMETERS pSearchText Text ( 255 );
INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown)
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
... and the rest
Save that query as qryGroupSearchAppend. Then you can execute that query from your VBA code:
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("qryGroupSearchAppend")
qdf.Parameters("pSearchText").Value = Me.txtgroupSearch.Value
qdf.Execute dbFailOnError

Classic ASP mysql INSERT getting result Operation is not allowed when the object is closed

I have this code:
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")
oConnection.Open "DRIVER={MySQL ODBC 5.1 Driver};SERVER=localhost;UID=xxxx;PWD=xxxx;DATABASE=xxxx; OPTION=3;"
Sqltemp = "INSERT INTO rsvptable (fname, lname, fbid, rsvp, streetaddress, city, state, zip, streetaddress2, cellphone, acode) " & _
"VALUES ('" & firstName & "', '" & lastName & "', " & fb & ", 0, '" & address1 & "', '" & city & "', '" & strState & "', " & zip & ", '" & address2 & "', " & cell & ", " & returnedNums & ")"
set newAdd = oConnection.execute(Sqltemp)
if newAdd.EOF then
response.write "end"
else
response.write "not end"
end if
And it keeps telling me this:
ADODB.Recordset error '800a0e78'
Operation is not allowed when the object is closed.
/add.asp, line 136
line 136 is this:
if newAdd.EOF then
What would i be overlooking here?
UPDATE
found my answer here! :o)
How to tell if a db update was successful?
two things:
you define oRecordset as the recordset, but then use & check eof on newAdd
Why are you trying to populate a recordet from an insert query?
http://www.w3schools.com/ado/met_conn_execute.asp
The results are stored in a new Recordset object if it is a
row-returning query. A closed Recordset object will be returned if it
is not a row-returning query.
INSERT is not a row-returning query, thus it returns a closed recordset, thus you can't .EOF it. Check the Rows Affected bu passing a variable as the second argument to Execute. If RowsAffected is 1, then you're set.