Retrieve data from table a, insert into Table B along with other fields - sql

I am trying to combine the two Sql Commands so that I can populate the data field with the text from the Select Command See below; I would like the text “Note Goes Here” to be replaced with the data from the selectcommand. However I am not sure how to do it.
Dim selectCommand As String = "Select Notes from Note Where NoteKey = " & lngNoteKey
strsql = "Insert into Activity (userName,pVisits,timeDate,data,flag)" _ & " Values('" & GetUserName() _ & "', '" & currentPage & "', '" & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & "', '" & "Note Text Goes Here" & "','" & "2" & "')"
I'm new to asp.net and vb and sql so be gentle

Generally speaking, any INSERT statement of the form
INSERT (a, b, c)
VALUES ( 'constant', 'constant', X from some table Y where Z)
can be replaced with
INSERT (a, b, c)
SELECT 'constant', 'constant', X
FROM Y
WHERE Z
So you'd want some SQL similar to this:
INSERT Activity (userName, pVisits, timeDate, data, flag)
SELECT #UserName, #PVisits, GETDATE(), Notes, 2
FROM Note
WHERE NoteKey = #NoteKey

You can use multiple queries on same command and use parameter to protect from sql injecttion:
Dim connection As New SqlConnection("Data Source=TEst//TEst;Initial Catalog=cMind_ProgramGuide;Persist Security Info=False;")
Dim strsql As String = "Insert into Activity (userName,pVisits,timeDate,data,flag) Select #userName,#pVisits,#timeDate,Notes,#flag from Note Where NoteKey = #note"
Dim Command As New SqlCommand(strsql, connection)
Command.Parameters.Add("#userName", SqlDbType.NVarChar).Value = GetUserName()
Command.Parameters.Add("#pVisits", SqlDbType.NVarChar).Value = currentPage
Command.Parameters.Add("#timeDate", SqlDbType.DateTime).Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
Command.Parameters.Add("#note", SqlDbType.NVarChar).Value = lngNoteKey
Command.Parameters.Add("#flag", SqlDbType.Int).Value = 2
connection.Open()
Command.ExecuteNonQuery()
connection.Close()

Related

MySqlException: Column count doesn't match value count at row 1

I am trying to save multiple data to my database with this code:
repNo = MainForm.StaffMixname.Text.Substring(0, 3) & DateTime.Now.ToString("yyyyMMddhhmmss")
MetroGrid5.DataSource = Nothing
Dim ds As DataSet = New DataSet
Dim Query As String = "SELECT ci.seq_id, CONCAT(ci.lastname, ci.firstname) AS fullname, ci.amountApplied, ci.province, co.kind, co.specifications, co.regOwner, co.location FROM clientinformation ci LEFT JOIN collateraloffered co ON ci.seq_id=co.seq_id WHERE co.kind IS NOT NULL AND ci.province = '" & MetroComboBox8.Text & "' AND ci.seq_id BETWEEN '" & convertedstrFrom.ToString("yyMMdd") & "%' AND '" & convertedstrTo.ToString("yyMMdd") & "%'"
Dim fetch As New MySqlDataAdapter(Query, connect)
fetch.Fill(ds, "collateral")
MetroGrid5.DataSource = ds.Tables("collateral")
If MetroGrid5.Rows.Count > 0 Then
Dim cm As New MySqlCommand
With cm
.Connection = connect
For i As Integer = 0 To MetroGrid5.RowCount - 1
.CommandText = _
"INSERT INTO collateralrpt Values('" & repNo & _
"', '" & MetroGrid5.Rows(i).Cells("seq_id").Value & _
"', '" & MetroGrid5.Rows(i).Cells("fullname").Value & _
"', '" & MetroGrid5.Rows(i).Cells("amountApplied").Value & _
"', '" & MetroGrid5.Rows(i).Cells("kind").Value & _
"', '" & MetroGrid5.Rows(i).Cells("specifications").Value & _
"', '" & MetroGrid5.Rows(i).Cells("regOwner").Value & _
"', '" & MetroGrid5.Rows(i).Cells("location").Value & _
"', '" & MetroGrid5.Rows(i).Cells("province").Value & "')"
.ExecuteNonQuery()
Next
End With
cm.Dispose()
cm = Nothing
With connect
.Close()
.Dispose()
End With
Else
MsgBox("No Data!")
End If
but unfortunately It shows MySqlException Column count doesn't match value count at row 1.
Is there any mistake with the code above? thanks in advance.
If you want to retrieve data from one table(s) and insert into another, just use a single data adapter. You can even do so if the tables are in a different database - you just need a different connection for the SelectCommand and InsertCommand. Only a single connection is required for a single database though. E.g.
Dim selectSql = "SELECT Column1A, Column1B FROM Table1"
Dim insertSql = "INSERT INTO Table2
(
Column2A,
Column2B
)
VALUES
(
#Column2A,
#Column2B
)"
Using connection As New MySqlConnection("connection string here"),
insertCommand As New MySqlCommand(insertSql, connection),
adapter As New MySqlDataAdapter(selectSql, connection) With {.InsertCommand = insertCommand, .AcceptChangesDuringFill = False}
With insertCommand.Parameters
.Add("#Column2A", MySqlDbType.Int, 0, "Column1A")
.Add("#Column2B", MySqlDbType.VarChar, 50, "Column1B")
End With
Dim table As New DataTable
connection.Open()
adapter.Fill(table)
adapter.Update(table)
End Using
There are a few things to note here.
I wrote the SQL code using a single, multiline literal. That is far
more readable that concatenating every line.
I used parameters. That prevents numerous issues that have been
written about ad nauseum so I won't go into it here.
There's no grid control involved here. You can add one and bind the DataTable after calling Fill but that is only so you can see the data. It has nothing to do with the actual code of retrieving and saving.
The connection is opened explicitly. You can normally let a Fill or Update call open and close the connection implicitly but, in this case, we want to perform both operations and closing and reopening the connection in between is an unnecessary overhead.
The disposable objects are created with a Using statement, which means they will be implicitly disposed at the end of the block. That inclides closing the connection.
The AcceptChangesDuringFill property of the data adapter is set to True so that all RowStates are left as Added so that all DataRows are ready to be inserted.

vb.net sql parameter incorrect syntax near 'value'

I'm new here, I'm trying to convert an integer into varbinary to insert into an already made SQL table. I've included the code, I get incorrect syntax near "523641" which is the HOUSE_ID I am trying to convert.
I also converted the int to byte array and added a parameter to the command but same result
Dim varbin As String = " convert(varbinary, '" & houseid & "')"
obj = objCon.CreateCommand()
strSQL = "insert into " & tbl & " (hello, HOUSE_ID, world) VALUES ('" & hello & "','" & varbin & "','" & world & "')"
obj.CommandText = strSQL
obj.ExecuteNonQuery()
Expected result is putting that 523641 into the varbinary(50) column.
Not sure why you would want to store an integer in a varbinary column but you can use BitConverter along with a parameterized query. Always use parameters instead of string concatenation for values that vary by execution as parameters have a number of benefits for security, performance, and ease of use.
Dim varbin As Byte() = BitConverter.GetBytes(houseid)
obj = objCon.CreateCommand()
strSQL = "insert into " & tbl & " (hello, HOUSE_ID, world) VALUES (#hello, #varbin, #world);"
obj.Parameters.Add("#hello", SqlDbType.VarChar, 50).Value = hello
obj.Parameters.Add("#varbin", SqlDbType.VarBinary, 50).Value = varbin
obj.Parameters.Add("#world", SqlDbType.VarChar, 50).Value = world
obj.CommandText = strSQL
obj.ExecuteNonQuery()

data is not inserted to database

i tried to insert the data into database with this code
Public Sub AddUser()
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id='" & WorkerID_.Text & "'"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
Dim reader As OleDbDataReader
Dim da As New OleDbDataAdapter
con.open()
reader = cmd.ExecuteReader()
reader.Read()
If reader.HasRows() Then
reader.Close()
con.close()
FailureText.Text = "User ID already exists!"
Else
reader.Close()
con.close()
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) VALUES "
InsertSQL &= "('" & WorkerID_.Text & "', "
InsertSQL &= "'Worker', "
InsertSQL &= "'12345', 1)"
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) VALUES (default,"
SqlUpdate &= "'" & WorkerID_.Text & "', "
SqlUpdate &= "'" & WorkerName.Text & "', "
SqlUpdate &= "'" & DoB.Text & "', "
SqlUpdate &= "'" & Address.Text & "', "
SqlUpdate &= "'" & Phone.Text & "', "
SqlUpdate &= "'" & Email.Text & "', "
SqlUpdate &= "'" & Company.SelectedValue & "', "
SqlUpdate &= "'" & PassNum.Text & "', "
SqlUpdate &= "'" & PassExp.Text & "', "
SqlUpdate &= "'" & VisaExp.Text & "', "
SqlUpdate &= "'No Visa', "
SqlUpdate &= "'" & WorkerID_.Text & "') "
Dim insertCommand As New OleDbCommand(SqlUpdate, con.oleconnection)
Dim cmd1 As New OleDbCommand(InsertSQL, con.oleconnection)
Try
con.open()
cmd1.ExecuteNonQuery()
insertCommand.ExecuteNonQuery()
Catch
FailureText.Text = "Unable to add user"
Finally
con.close()
End Try
End If
Response.Redirect("Workers.aspx")
End Sub
the Insert into login part is working. the data is well inserted. but for the insert into worker part is not working. the data is not inserted into the table. the program shows no error and it still can work. what could possibly wrong with this?
Read another answer on OleDb I just answered on another post. You will be wide open to sql-injection too. Parmaeterize queries. By you concatenating strings to build one command, what if one value has a single-quote within the text entry. You are now hosed. What if someone puts malicious SQL commands and then deletes your records or entire table(s). Learn to parameterize your queries and also clean values, especially if coming from a web interface.
Your commands should probably be updated something like
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id= #parmUserID"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
cmd.Parameters.AddWithValue( "parmUserID", WorkerID_.Text )
Follow-suit with the Insert and update commands... parameterize them but using #variable place-holders in your commands.
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) "
InsertSQL &= " VALUES ( #parmUser, #parmRole, #parmPwd, #parmStatus )"
Dim cmdInsert As New OleDbCommand(InsertSQL, con.oleconnection)
cmdInsert.Parameters.AddWithValue( "parmUser", WorkerID_.Text )
cmdInsert.Parameters.AddWithValue( "parmRole", "Worker" )
cmdInsert.Parameters.AddWithValue( "parmPwd", "12345" )
cmdInsert.Parameters.AddWithValue( "parmStatus", 1 )
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) "
SqlUpdate &= " VALUES ( #parmID, #parmName, #parmDoB, etc... ) "
Dim cmdUpdate As New OleDbCommand(SqlUpdate, con.oleconnection)
cmdUpdate.Parameters.AddWithValue( "parmID", WorkerID_.Text )
cmdUpdate.Parameters.AddWithValue( "parmName", WorkerName.Text )
cmdUpdate.Parameters.AddWithValue( "parmDoB", DoB.Text )
-- etc with the rest of the parameters.
Final note. Make sure the data types you are trying to insert or update are of same type expected in the table. Such example is your "Birth Date" (DoB) field. If you are trying to insert as simple text, and it is not in an auto-converted format, the SQL-Insert might choke on it and fail. If you have a textbox bound to a DateTime type, then your parameter might be Dob.SelectedDate (such as a calendar control), or you could pre-convert from text to a datetime and then use THAT as your parameter value.
Other numeric values, leave as they are too, they should directly apply for the insert. You could also identify the AddWithValue() call the data type the parameter should represent (string, int, double, datetime, whatever)
You seem to have 12 parameters you wish to insert, and 13 arguments in the VALUES part of your insert query. is the Default seen in the values section below intentional?
INSERT INTO Worker (ID, ... VisaStatus) VALUES (default,"
ensure you have the correct number of parameters defined and added, then let us know, but i could be missing something else.

Can't insert into acces db with .net

I used this site to get me on my way with the Insert command, however, i can't get it to work.
How can I insert data into 2 different table in VB.net, I'm using MS Access as my db
I got 3 tables, 1 with foodtypes, 1 with (basically) menus and 1 connecting table that connect the id of a menu with the ID's of sfoodtypes.
I try to use a query to create new menu's. however, a error occures:
There is ; missing in the sql string
Str = "INSERT INTO tbl_rantsoen (Rantsoen, Voer, Gewicht) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text) WHERE RantsoenID = tblRantsoen.RantsoenID, Voer = '" & cbVoer.Text & "', Gewicht = '" & tbGewicht.Text & "'"
Now, i tried different places to place the ; but cant find the right spot. Can anyone help me?
The rest of the code::
EDIT:(and clean-up)
I made some changes based on the comments below, but i still get the ; missing error.
Dim cmd As New OleDbCommand
Dim cmd1 As New OleDbCommand
Dim cmd2 As New OleDbCommand
Dim Str As String
Dim Str1 As String
Dim Str2 As String
Str = "INSERT INTO tbl_rantsoen (Rantsoen, Voer, Gewicht) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text); " 'WHERE RantsoenID = tblRantsoen.RantsoenID, Voer = '" & cbVoer.Text & "', Gewicht = '" & tbGewicht.Text & "'"
Str1 = "INSERT INTO tbl_voersoorten (VoerID, Voer) VALUES (cbVoer.text) WHERE Voer = '" & cbVoer.Text & "'"
Str2 = "INSERT INTO tbl_rantsoenKoppel (VoerID, RantsoenID) VALUES() WHERE RantsoenID = tbl_rantsoenkoppel.FKRantsoenID AND VoerID = tbl_voersoorten.VoerID"
connection.Open()
cmd = New OleDbCommand(Str, connection)
cmd1 = New OleDbCommand(Str1, connection)
cmd2 = New OleDbCommand(Str2, connection)
cmd.ExecuteNonQuery()
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
You can't use WHERE clauses in your INSERT command
and if you want execute more than one command in single CommandTextyou should to seperate them with ;.
and finally:
Str = "INSERT INTO tbl_rantsoen (Rantsoen, Voer, Gewicht) VALUES ('" & cbRantsoen.text & "', '"& cbVoer.text & "','"& txtGewicht.text & "')"
Str1 = "INSERT INTO tbl_voersoorten ( Voer) VALUES ('" & cbVoer.text & "')"
and for query Str3 you should to get related id from last two query and insert them into 3th query ;)
Your INSERT Syntax is wrong. There cannot be a WHERE Clause.
INSERT INTO TableName (Column1,Column2,Colum3) VALUES(Value1,Value2,Value3);
If you are trying to change an existing record, try using the UPDATE Clause
UPDATE TableName SET Column1 = Value1 , Column2 = Value2, Column3 = Value3 WHERE Condition1 = Condition2 AND Condition3 = Condition4

Multiple if statements, then, or else?

I'm having some problems getting a query to run based off another query. Here's the database diagram to give a little background. The primary keys for all the tables are automatically generated by identites. The first 2 insert statements (Donation and Food_Donation) work but I can't get the last insert into Donation_Details to work. Here's the code so far:
Dim con As New OleDbConnection(DBcon)
Try
Dim dr As OleDbDataReader
Dim command As New OleDbCommand("Insert into Donation (Donor_ID) VALUES ( " & txtDonNum.Text & "); Select ##Identity;")
con.Open()
command.Connection = con
dr = command.ExecuteReader
Dim Donation_ID As String = ""
If dr.Read() Then
Donation_ID = dr(0).ToString
Dim food As New OleDbCommand("Insert into Food_Donation (Date_Received, Donation_ID) Values ( '" & maskedreceived.Text & "', " & Donation_ID & "); Select ##Identity")
food.Connection = con
food.ExecuteNonQuery()
End If
Dim Food_ID As String = ""
If dr.Read() Then
Food_ID = dr(0).ToString
Dim food2 As New OleDbCommand("Insert into Donation_Details (Quantity, Unit, Expiration_Date, Food_ID, Storage_ID, Type_ID) Values ( " & txtQuantity.Text & ", '" & boxUnit.Text & "', '" & maskedexpire.Text & "', " & Food_ID & ", " & txtStorageID.Text & ", " & txtTypeID.Text & ")")
food2.Connection = con
food2.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Close()
End Try
End sub
I'm fairly correct my SQL statements are correct and it's just whether or not the last statements need to be an If or something else.
You should be using dr = food.ExecuteReader() rather than food.ExecuteNonQuery() if you want to reuse dr to acquire Food_ID?
I suspect your problem is that you're using If dr.Read() twice.
The dr.Read() method will move the reader forward to the next row but you are only selecting a single value in your initial query.
So, for example, your reader (being made from the insert) will return a single row value for the successful insert. Calling Read() on it will succeed but then move the row cursor to EOF causing subsequent Read() calls to return FALSE