I am inserting two values to a table, one from another table and the other from form control but I am getting an error.
sqlstr = "INSERT INTO partylinks ( accountid, partyid ) values(Select max(accountsinfo.accid) FROM accountsinfo,2 )"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.ExecuteNonQuery()
You don't use the VALUES syntax if you are SELECTing
Try:
sqlstr = "INSERT INTO partylinks (accountid, partyid) Select max(accountsinfo.accid),2 AS partyid FROM accountsinfo"
Related
when try to insert a data on my database it always received a null value
here is my code,
query = "INSERT INTO tbl_Inventory (Asset_Code,Item_Name,Category,Location,Serial_No,Description,Date_Acquired,Date_Inventory,Remarks,Item_Status)" _
"VALUES (#assetcode , #itemname , #category, #location, #serialNo, #description, #dateacquired, #dateinventory, #remarks, #itemstatus)"
Dim cmd As New Odbc.OdbcCommand(query, conn)
cmd.Parameters.AddWithValue("#assetcode", varasset)
cmd.Parameters.AddWithValue("#itemname", txtItemName.Text)
cmd.Parameters.AddWithValue("#category", txtcategory.Text)
cmd.Parameters.AddWithValue("#location", txtLocation.Text)
cmd.Parameters.AddWithValue("#serialNo", txtSerialNo.Text)
cmd.Parameters.AddWithValue("#description", txtDescription.Text)
cmd.Parameters.AddWithValue("#dateacquired", txtDateAcquired.Text)
cmd.Parameters.AddWithValue("#dateinventory", txtdateInventory.Text)
cmd.Parameters.AddWithValue("#remarks", txtRemarks.Text)
cmd.Parameters.AddWithValue("#itemstatus", cmbstatus.SelectedText)
cmd.ExecuteNonQuery()
I am trying to execute 2 queries.
First one should insert data (especially "product") or update in case the db already has a row with such title.
Second one should insert new category for product which was inserted\updated from 1st query and ignore any inserts, if table already has such product with such category
Here is my code :
conn = DatabaseConnection.getConnection();
stmt = conn.createStatement();
conn.setAutoCommit(false);
String updateSQL = "INSERT INTO product (title, price, `status`) " +
"VALUES(?, ?, ?)" +
"ON DUPLICATE KEY UPDATE price = ?, `status` = ?;"
PreparedStatement preparedStatement = conn.prepareStatement(updateSQL);
preparedStatement.setString(1, product.getTitle());
preparedStatement.setBigDecimal(2, product.getPrice());
preparedStatement.setInt(3, product.getStatus().ordinal());
preparedStatement.executeUpdate();
updateSQL = "INSERT IGNORE INTO product_categories (product_id, category_id) " +
"VALUES (last_insert_id(), ?);";
preparedStatement = conn.prepareStatement(updateSQL);
preparedStatement.setLong(1, categoryId);
preparedStatement.executeUpdate();
conn.commit();
So, the problem is that I use last_insert_id() which means that i will use incorrect row in 2nd query if 1st query just updated the data.
So, I would like to know how could I synchronize these 2 queries.
Since you don't have access to last_insert_id() in the second query, you'll have to fetch it as in the answers for this question.
Here's an example:
...
preparedStatement.executeUpdate(); // this is the first query
ResultSet rs = preparedStatement.getGeneratedKeys();
if ( rs.next() )
{
long last_insert_id = rs.getLong(1);
updateSQL = "INSERT IGNORE INTO product_categories (product_id, category_id) " +
"VALUES (?, ?);";
preparedStatement = conn.prepareStatement(updateSQL);
preparedStatement.setLong(1, last_insert_id);
preparedStatement.setLong(2, categoryId);
preparedStatement.executeUpdate();
}
conn.commit();
If the first query didn't result in an INSERT, then there isn't enough information to add the product to the product_category, in which case this is skipped all together. This does assume that the product is already in the category. If you're not sure about that, and want to execute the second query regardless, you could query for the product_id:
SELECT id FROM product WHERE title = ?
and then use that id instead of the last_insert_id variable, or, you could change the second query and use title as a key (although I'd stick with an id):
INSERT IGNORE INTO product_categories (product_id, category_id)
VALUES (SELECT id FROM product WHERE title = ?), ?)
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
I migrated from Access to Mysql.Codes for vb6.
mobjCmd.CommandText = "INSERT INTO The123 SELECT The1 AS FirstName FROM schedule"
Set mobjRst = mobjCmd.Execute
And this query is not working in Mysql.
mobjCmd.CommandText = "INSERT INTO The123 VALUES("yOUR VALUES")"
MOBJCMD.COMMANDTEXT = "SELECT The1 AS FirstName FROM schedule"
Set mobjRst = mobjCmd.Execute
You must divide two CMD
You need to specify column for The123 table
mobjCmd.CommandText = #"INSERT INTO The123 (FirstName) SELECT The1 AS FirstName FROM schedule"
Set mobjRst = mobjCmd.Execute
I was asked to create a program that inserts records into one parent table and multiple child tables. My question is, how do I know what the PK is for the parent table, so that I may add it as a FK in the child? The PK for the parent is an auto number. As I stated in my title, I'm using VB.net, mySQL, through an ODBC connection. I have to do this through the code and cannot use stored procedures. Any suggestions?
thanks
my transaction looks like this:
Dim cmdText As String = "INSERT INTO candidate(first_name, last_name, phone1, phone2, email1, city, " _
& " state, country, zip,primary_contact_id ) VALUES (?,?, ?, ?,?,?, ?,?,?,?)"
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim SqlStatus As Integer
Dim trans As Odbc.OdbcTransaction = conn.BeginTransaction(IsolationLevel.ReadCommitted)
Dim cmd As OdbcCommand = New OdbcCommand(cmdText, conn, trans)
Try
cmd.Parameters.Clear()
cmd.CommandType = CommandType.Text 'The default is CommandType.Text
With cmd.Parameters
.Add("#first_name", OdbcType.VarChar).Value = fName
.Add("#last_name", OdbcType.VarChar).Value = lName
.Add("#phone1", OdbcType.VarChar).Value = phone
.Add("#phone2", OdbcType.VarChar).Value = mobilePhone
.Add("#email1", OdbcType.VarChar).Value = email
.Add("#city", OdbcType.VarChar).Value = city
.Add("#state", OdbcType.VarChar).Value = state
.Add("#country", OdbcType.VarChar).Value = country
.Add("#zip", OdbcType.VarChar).Value = zip
.Add("#primary_contact_id", OdbcType.Int).Value = getContactFK
End With
SqlStatus = cmd.ExecuteNonQuery
If Not SqlStatus = 0 Then
trans.Commit()
Me.Close()
Else
MsgBox("Not Updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
trans.Dispose()
End Try
I'm still working on the code, so not sure if it works just yet
jason
Take a look at How to Get the Unique ID for the Last Inserted Row
Since you're going through ODBC and cannot use a stored proc you will have to execute two SQL statements together (as a batch). First your insert and then SELECT LAST_INSERT_ID()
It should look something like:
INSERT INTO ... ;
SELECT LAST_INSERT_ID();
Since you're expecting a result you need to execute from your client code as a SELECT statement. And since this is a batch operation with an insert you should also consider using a transaction.
You can use
"; select last_insert_id()"
At the end of your insert for the parent table. And then use
Dim id as Integer = cint(command.ExecuteScalar())
To get the resulting key to use in the child inserts