Cannot successsfully parse mysql database info - mysql
I'm trying to call a procedure in a module that needs some arguments, thus:
MySQL code to be executed (extracted from the module's procedure):
Sub InsertRecord(ByVal tbl As String, ByVal cols() As String, ByVal params() As String, ByVal colCondition As String, ByVal paramCondition As String) 'As String
:
:
comA.CommandText = "INSERT INTO " & tbl & " (" & newCols & ") SELECT * FROM (SELECT #params) AS tmp "
comA.CommandText &= "WHERE NOT EXISTS (SELECT " & newCols & " FROM " & tbl & " WHERE " & colCondition & " = #param) limit 1"
comA.Parameters.AddWithValue("#param", paramCondition)
comA.Parameters.AddWithValue("#params", newParams)
:
:
End Sub
Call Code:
myModule.SaveInfo("myprod", {"col_a", "col_b", "col_c", "col_d", "col_e", "col_f", "col_g", "col_h"}, _
{val_a, val_b, val_c, val_d, val_e, val_f, val_g, val_h}, "col_b", val_b)
hint: newCols and newParams (obtained from cols() and params() respectively) are comma-delineated lists of columns of the table in question and values to be inserted respectively.
When i run my code, i get the error: column count doesn't match value count at row 1
Please how do i address this issue? I've been on it for some days now.
Thanks in advance.
Edit:
I decided to write the code on the sub, instead of using a module. Here is the full subroutine:
Private Sub SaveProduct(ByVal p_code As String, ByVal b_id As String, ByVal m_id As String, _
ByVal c_id As String, ByVal des As String, ByVal o_det As String)
'modNewData.InsertRecord("products", {"prd_code", "brnd_id", "mnu_id", "cat_id", "prd_description", "prd_details", "prd_create_date", "prd_last_update"}, _
' {p_code, b_id, m_id, c_id, des, o_det, Date.Now.ToShortDateString, Date.Now.ToShortDateString}, "brnd_id", b_id)
con = New MySqlConnection("Server=localhost; Database=inventory_db; Uid=root; Pwd=;")
comA = New MySqlCommand
'INSERT NEW RECORD.
comA.CommandText = "INSERT INTO products (prd_code, brnd_id, mnu_id, cat_id, prd_description, prd_details, prd_create_date, prd_last_update) "
comA.CommandText &= "SELECT * FROM (SELECT #params) AS tmp "
comA.CommandText &= "WHERE NOT EXISTS (SELECT prd_code, brnd_id, mnu_id, cat_id, prd_description, prd_details, prd_create_date, prd_last_update FROM products "
comA.CommandText &= "WHERE brnd_id = #param) limit 1"
comA.Parameters.AddWithValue("#param", b_id)
comA.Parameters.AddWithValue("#params", {p_code, b_id, m_id, c_id, des, o_det, Date.Now.ToShortDateString, Date.Now.ToShortDateString})
comA.Connection = con
con.Open()
comA.ExecuteNonQuery()
con.Close()
'Release used up components
comA.Parameters.Clear()
comA.Dispose()
comA = Nothing
con = Nothing
MsgBox("done.")
At this point, i don't seem to know what i'm doing, but I know what i want to achieve - insert a new record in a table. I strongly believe that there's a problem with my sql code, but can't figure out exactly what it is. Your help is highly needed at this point. Thanks in advance.
EDIT 2:
I tweaked the mysql insert code above, and now i can successfully insert new record to my table. But one more problem exists: I get this <Unable to read data> error in my datetime and timestamp columns respectively.
id prd_code brnd_id mnu_id cat_id desc details create_date (datetime) last_update(timestamp)
10 PM-16326 10 9 6 Red NULL 10/15/2013 8:22:00 AM 7/16/2015 9:13:03 AM
17 PM-55326 23 28 11 Olive oil n/a <Unable to read data> <Unable to read data>
Here's the new insert code:
'INSERT NEW RECORD.
comA.CommandText = "INSERT INTO products (prd_code, brnd_id, mnu_id, cat_id, prd_description, prd_details, prd_create_date, prd_last_update) "
comA.CommandText &= "SELECT * FROM (SELECT #p_code, #b_id, #m_id, #c_id, #des, #o_det, '11/11/2015 9:00:00 AM', '11/12/2015 9:00:00 AM') AS tmp "
comA.CommandText &= "WHERE NOT EXISTS (SELECT prd_code, brnd_id, mnu_id, cat_id, prd_description, prd_details, prd_create_date, prd_last_update FROM products "
comA.CommandText &= "WHERE brnd_id = #b_id) limit 1"
comA.Parameters.AddWithValue("#p_code", p_code)
comA.Parameters.AddWithValue("#b_id", b_id)
comA.Parameters.AddWithValue("#m_id", m_id)
comA.Parameters.AddWithValue("#c_id", c_id)
comA.Parameters.AddWithValue("#des", des)
comA.Parameters.AddWithValue("#o_det", o_det)
If i replaced the two dates above with date.now.tostring, I'll get the error: you have repeated columns...
I really need your help guys. Thanks in advance.
The columns you pass to the procedure (which do match) are called cols, but in the query you use newCols.
The MySQL error you get means that the values you insert are not in the same number as the columns you say they should fill: you cannot insert four values into five columns, or three.
So what is happening is clearly that you do something to retrieve newCols from cols, in the part of code you have omitted. Probably, depending on some condition, you add some columns (or leave some out). That is what is causing your trouble. You should modify at the same time, apparently, the value of params into some other value, possibly newParams.
Also, perhaps the condition is not always true, and you observe the function misbehaving only occasionally, or passing some test (because that test does not trigger the column-modifying bug).
Related
Insert Into (select from ) with multifield values and specific values
I am trying to insert mulivalues of swab locations into a table that has the same tracking number. Here is the example: tblMainSwapLocation (Table where i get my information form) Asset_ID MAterial Swap_Location MFG111 Brick Top left MFG111 Plastic Top right MFG113 Wood Center tblCVLocation (Table where i want to insert information into) TrackingID Asset_ID Swap_Location 99801 MFG111 Top left 99801 MFG111 Top right I am using the following sql query to do the job, but i am having troubles with how the query should be. strSQL = "Insert Into tblCVProject " & vbCrLf strSQL = strSQL & "Values ( [pTrackNum], (SELECT MEQ.Asset_ID ,MEQ.SwabLocation" & vbCrLf strSQL = strSQL & "FROM tblMainSwapLocation as MEQ " & vbCrLf strSQL = strSQL & "WHERE MEQ.Asset_ID = [pAsset_ID] ))" Debug.Print strSQL Set qdf = dbs.CreateQueryDef(vbNullString, strSQL) qdf.Parameters("pAssetID").Value = Me.cboAsset_Id qdf.Parameters("pTrackNum").Value = TrackNum The query in simplier form, It runs when the user clicks the save button. Insert Into tblCVProject Values ( [pTrackNum], (SELECT MEQ.Asset_ID ,MEQ.SwabLocation, MEQ.Equipment_Name FROM tblMainSwapLocation as MEQ WHERE MEQ.Asset_ID = [pAsset_ID] )) This is the error I am getting:
The syntax of the INSERT statement is well explained at: https://msdn.microsoft.com/en-us/library/bb208861(v=office.12).aspx Either use VALUES (for single-record append query) or SELECT for multi-record append query.
Not enough info to give a clear answer. I have guessed that your TrackingID column is defined as auto-number because I see nowhere a source for it If you want to generate a record in tblCVLocation for each tblMainSwapLocation then you just have to do this : INSERT INTO tblCVProject ([Asset_ID],[Swap_Location]) SELECT Asset_ID, Swap_Location FROM tblMainSwapLocation If you want to insert only for some Asset_ID or material, then add a WHERE clause after the SELECT If you want only the distinct pairs of Asset_ID + Swap_location then add a DISTINCT clause in the SELECT I really can be more accurate with the information specified
Unknown table in field list (MySQL in vb.net)
I use MySql.Data.MySqlClient.MySqlCommand and MySqlConnection Public fillGridCmdTxt As String = "SELECT tblItems.part_num AS Part#, tblCategory.category_description AS Category, " _ & " tblItems.item_name AS 'Item Name', tblItems.item_desc AS Description, " _ & "tblItems.item_qty AS Qty, tblUnit.unit_name AS Unit, tblItems.item_price AS 'Selling Price(Php)' " _ & "FROM tblUnit INNER JOIN tblItems ON tblUnit.unit_id = tblItems.unit_id INNER JOIN tblCategory " _ & "ON tblItems.category_id = tblCategory.category_id " and when i use executeNonQuery on MySqlCommand, it gives me an error... It says that "Unkown table '*tblItems in field list*" even the table is really existing on my database... a little help please?
You need to enclose Part# between quotes. The # sign starts a comment in MySQL, so your whole statement is read as just SELECT tblItems.part_num AS Part. The error message tells you that you are naming a table in the fields list that you didn't specify in the FROM list (because the FROM list got commented out).
How to avoid duplicate entries in access from vb6?
I am using Vb6 and Access 2007. I am adding records to the access table name "subjectcode" from vb6. The details of subjectcode table are below. Subjectcode table : Heading(Degree,Branch,Year1,Year2,Semester,Subjectcode,Subjectname,Theory_Practical, Major_Allied_Elective) values (Bsc,computerscience,2001,2004,1,RACS1,Vb6 programming,Theory,Major) Note :The primary key in the above table is Degree,Branch,Year1,Year2,Semester,Subjectcode And the code i used to add entry to the access table from vb6 are given below : If degree = "" Or branch1 = "" Or year1 = "" Or year2 = "" Or semester = "" Or subcode.Text = "" Or subname.Text = "" Or theory.Text = "" Or major.Text = "" Then MsgBox "Fields can't be empty ! All are mandatory!" Else rs.Open "select * from subjectcode", con, 1, 3 rs.AddNew rs!degree = degree rs!branch = branch1 rs!year1 = year1 rs!year2 = year2 rs!semester = semester rs!Subjectcode = subcode.Text rs!Subjectname = subname.Text rs!Theory_Practical = theory.Text rs!Major_Allied_Elective = major.Text rs.Update MsgBox "Successfully Saved !", vbOKOnly + vbInformation, "info" rs.Close End If And the screenshot of that Add form of vb6 is here: http://tinypic.com/r/w7c7if/6 The record is added when the same entry is not exist. And if the record is already exist it should say "Record Already exists" and i don't know how to do that. Could you guys give me idea please.
Write a save method to save your record, and a method to query the database and check for an existing record before you save the data. Public Sub SaveSubjectCode(ByVal vDegree As String, ByVal vBranch As String, ByVal vYear1 As Integer, ByVal vYear2 As Integer, ByVal vSemester As Integer, ByVal Subjectcode...) If (DoesRecordExist(vDegree, vBranch, vYear1, vYear2, vSemester, vSubjectcode) = True Then ' Warn the user MessageBox("I'm sorry Dave I can't do that. The record already exists.") Else ' Save the record End If End Sub Private Function DoesRecordExist(ByVal vDegree as String, ByVal vBranch As String, ByVal vYear1 As Integer, ByVal vYear2 As Long, ByVal vSemester As Integer, ByVal vSubjectcode As String) As Boolean RecordSet = query 'Query the database for the existing record If RecordSet.BOF And RecordSet.EOF Then DoesRecordExist = False Else DoesRecordExist = True End If End Function Also, you want to avoid the the Select * query that selects every record unless you really need it because it is likely to be slow, and get slower as the number of records grow. If you want to get a recordset just to use to add a new record you can include a Where clause that does not return any records "select * from subjectcode WHERE 1 = 2, con, adOpenKeyset, adLockOptimistic
When you create a field in a table you specify whether duplicates are allowed or not. Then an offending add or update raises an exception. The SQL DML looks like: ALTER TABLE tblCustomers ADD CONSTRAINT CustomerNames UNIQUE ([Last Name], [First Name]) And there are other powerful features such as check contraints as well: ALTER TABLE tblInvoices ADD CONSTRAINT CheckAmount CHECK (Amount > 0) One advantage of constraints is that your database's integrity is not held hostage by rogue applications that may fail to do chatty pre-qualification queries (or fail to implement them properly). Another is the performance improvement over chatty techniques and the fact that when there are multiple updaters the database can change between pre-qual query and update.
SQL Select statement wont return char fields only numeric fields
I have been racking my brain over this all day today. I have the following ASP code that uses a Request.Querystring input from a dropdown box to launch a select statement. The querystrinch does show in the ?= URL but will only work on columns in the Microsoft SQL DB that are numeric. I cant lookup names or simple 3 character fields. CODE: If Request.QueryString("m") > 0 Then filterID = Request.QueryString("m") filterColmn = "imDegree" Else filterID = 0 End If If filterID > 0 Then SQlQuery = "SELECT * FROM v_InternImport WHERE iID IN (SELECT iID FROM v_InternImport WHERE " & filterColmn & " = " & filterID & ")" End If End If I understand that this select statement as a sub select stament in it but I cant even get a staight reuturn from my DB. The select statement references the same view that populates the main asp page that loads before and the shows fine?
When you pass a string to SQL Server, you need to surround it with single quotes. When you pass a number, you don't use the quotes. So, when you say (summarizing) SELECT * FROM table WHERE filterColumn = filterID you should be sending a number. To match a string: SELECT * FROM table WHERE filterColumn = 'filterID' This assumes that you have solved any other problems mentioned by the commenters about whether you even have a value in the filterID variable. I heartly concur with the recommendation to use parameterized queries. Edit: The single quotes go inside the double quotes. SQlQuery = "SELECT * FROM v_InternImport WHERE iID IN (SELECT iID FROM v_InternImport WHERE " & filterColmn & " = '" & filterID & "')"
Returning unread records using Linq To SQL
I'm not sure how to ask this question, so I'll start with an example of what I'm doing. Here is my table structure... Documents (Primary key = ID) ID, Title, LatestApprovedRevID Revisions (Primary key = ID) ID, DocumentID, RevisionNum, Body Document_Reads (Primary key = DocumentID, UserName) DocumentID, UserName, RevisionID When a user opens a document, the latest approved revision is opened and a record is inserted into Document_Reads showing the document and revision the user had read. I would like to know how to query using Linq to return the documents that have NOT been read by UserName (the current authenticated user). To get the list of unread documents, there are three cases where I would like to return the document: if a document has no records in Document_Reads. if a document has records in Document_Reads, but none of them are for UserName. if a document has records in Document_Reads and one for UserName exists, but the Document_Reads.RevisionID does not match Documents.LastApprovedRevID. I have written a filter function, but I'm having problems writing the query for the 2nd requirement. It will return the document if any Document_Reads are found that do not match the UserName. <Runtime.CompilerServices.Extension()> _ Public Function FilterLatestUnread(ByVal query As IQueryable(Of Document), ByVal userName As String) As IQueryable(Of Document) 'Documents with no document_reads Dim q As IQueryable(Of Document) = From d In query _ Where d.Document_Reads.Count = 0 _ Select d 'documents with document_reads but none for userName q = q.Union(From d In query _ From dr In d.Document_Reads _ Where Not (dr.UserName = userName) _ Select d) 'documents with document_reads for userName but RevisionID does not match LastApprovedRevID q = q.Union(From d In query _ From dr In d.Document_Reads _ Where dr.UserName = userName And _ Not (dr.RevisionID = d.LastApprovedRevID) _ Select d) 'Return the combined query. Return q End Function Then, I have my repository return all documents that have an approved revision and use the filter like... return _repository.List().FilterLatestUnread("John Doe").ToList() Thanks for any help and I apologize if this topic can be found on this site already...I wasn't sure what I needed to search for.
I think I figured it out. For the second query, I'm using this code: q = q.Union(From d In query _ Where (From dr In d.Document_Reads _ Where dr.UserName = userName _ Select dr).Count = 0 _ Select d) Thanks bpayne for helping me talk it out!
Update: I had run into another error that had to do with trying to Union queries with a different number of expressions. This is what I had to do to fix it in the end... return From d In query _ Where (d.Document_Reads.Count = 0) Or _ (From dr In d.Document_Reads _ Where dr.UserName = userName _ Select dr).Count = 0 Or _ (From dr In d.Document_Reads _ Where dr.UserName = userName And _ Not (dr.RevisionID = d.LastApprovedRevID) _ Select dr).Count = 1 _ Select d