How to Insert data while Copying data in other Table - vb.net

My problem is, in one button (click event) I need to Copy a data in Table1 (the ToolName) to Table2 (into ToolName) and insert a description to the same row.
Table1
ID - ToolName - Quantity
Table2
ID - ToolName - Description
here`s my codes
Dim sqlquery As String = "INSERT INTO Table2 (ToolName) SELECT ToolName FROM Table1 WHERE ID = '" & DataGridView1.CurrentRow.Cells(0).Value.ToString & "' INSERT INTO Table2 (Description) VALUES ('" & TextBox1.Text & "')"
Dim cmd As New OleDbCommand(sqlquery, con)
con.Open()
cmd.ExecuteNonQuery()
MsgBox(" succesfully", vbInformation)
con.Close()

Parametrized queries have two main advantages:
Security: It is a good way to avoid SQL Injection vulnerabilities
Performance: If you regularly invoke the same query just with different parameters a parametrized query might allow the database to cache your queries which is a considerable source of performance gain.
Extra: You won't have to worry about date and time formatting issues in your database code. Similarly, if your code will ever run on machines with a non-English locale, you will not have problems with decimal points / decimal commas.
Try like this
Dim sqlquery As String= "INSERT INTO Table2 (ToolName,Descrption) SELECT ToolName,#Desc FROM Table1 WHERE ID = #Id"
Dim cmd As New OleDbCommand(sqlquery, con)
cmd.Parameters.Add("#Desc", SqlDbType.VarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Id", SqlDbType.VarChar, 50).Value = DataGridView1.CurrentRow.Cells(0).Value.ToString
con.Open()
cmd.ExecuteNonQuery()
MsgBox("succesfully", vbInformation)
con.Close()

Change Query syntax like below
Dim sqlquery As String = "INSERT INTO Table2 (ToolName)
SELECT ToolName FROM Table1
WHERE ID = '" & DataGridView1.CurrentRow.Cells(0).Value.ToString & "';
INSERT INTO Table2 (Description) VALUES ('" & TextBox1.Text & "')"
I think nothing is wrong in query just missing ; between 2 insert query.

Just break it down into two separate updates based on what you already have, use the following code and just pass the ToolName into your update statements
Dim Table_ As String = "getToolName"
Dim query As String = "SELECT ToolName FROM Table1 WHERE ID = '" & DataGridView1.CurrentRow.Cells(0).Value.ToString
Dim cmd As New OleDbCommand(query, con)
Dim da As New OleDbDataAdapter(cmd)
da.Fill(ds, Table_)
Dim dt As DataTable = ds.Tables(Table_)
Dim ToolName As String = dt.Rows(0)(0).ToString()

Related

Getting error on inserting date into sql database?

I'm inserting record into database but is getting error on the paremeter "Date". Any thoughts would be good.
myConnection.Open()
Dim sqlQry As String = "INSERT INTO MasterLabNumber (LabNumber, Location, Date)" + "VALUES(#LabNumber, #Location, #Date)"
Dim str As String
str = "SELECT * FROM MasterLabNumber WHERE (LabNumber = " & TextBox1.Text & ")"
Dim d As System.DateTime = DateTime.Now.ToString("yyyy/MM/dd")
Dim cmd As OleDbCommand = New OleDbCommand(sqlQry, myConnection)
cmd.Parameters.AddWithValue("#LabNumber", TextBox1.Text)
cmd.Parameters.AddWithValue("#Location", ComboBox1.Text)
cmd.Parameters.AddWithValue("#Date", d)
cmd.ExecuteNonQuery() <-- gets error here relating to adding the parameter date.
Yeah, that's cause Date is a reserve word which you are using in your insert statement. You need to escape it like below using []
INSERT INTO MasterLabNumber (LabNumber, Location, [Date])
Your insert statement should become
Dim sqlQry As String = "INSERT INTO MasterLabNumber (LabNumber, Location, [Date]) VALUES(#LabNumber, #Location, #Date)"

SQL query, field name paseed by reference vb.net

I'm having problems trying to make this work, I have this query on an application that Im writing in vb.net 2012:
Dim strSql As String = " SELECT * FROM Table_Master WHERE field & "'= ('" & txtCadena.Text & "')"
What I need is to have the option to choose the field that I'm querying writing the field name on a textbox.
Maybe something like:
strSql As String = string.format("SELECT * FROM Table_Master WHERE [{0}] = '{1}'", txtField.text, txtFieldValue.text.replace("'","''"))
This should work (only for text, not dates, numbers etc) but you have to know that it is not the best practice.
I finally made it doing this.
Dim Query As String
Dimm DT As DataTable = New DataTable
Query = "select Actual, Description, Unit_of_measurement from Table_ARTIClES WHERE NUMPART = '" & txtPartNum.Text & "'"
Dim Table As SqlDataAdapter = New SqlDataAdapter(Query, conn)
Table.Fill(DT)
lblInventory.Text = DT.Rows(0)("Actual").ToString

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

Getting Primary key values (auto number ) VB

I have a database on Access and I want to insert into 2 tables
ReportReq
req_sysino
I want to get the last value of primary key (auto numbered) and insert it into req_sysino
, I am stuck with this code and I dont know how to proccess
Private Function InsertSysInvToDB(intSysInv As Integer) As Integer
Dim strSQLStatement As String = String.Empty
Dim intNoAffectedRows As Integer = 0
Dim con As New OleDb.OleDbConnection("PROVIDER = Microsoft.ace.OLEDB.12.0; Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb")
Dim cmd As OleDb.OleDbCommand
Dim reqnum As String = "Select ##REQ_NUM from ReportReq"
strSQLStatement = "INSERT INTO req_sysino (Req_num, sysinvo_ID)" +
" VALUES (" & reqnum & "','" & intSysInv & ")"
cmd = New OleDb.OleDbCommand(strSQLStatement, con)
cmd.Connection.Open()
intNoAffectedRows = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return intNoAffectedRows
End Function
this is my insert code that should generate autonumber
Dim dbProvider = "PROVIDER = Microsoft.ace.OLEDB.12.0;"
Dim dbSource = " Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb"
Dim sql = "INSERT INTO ReportReq (Emp_EmpID, Req_Date,Req_expecDate,Req_repnum, Req_name, Req_Descrip, Req_columns, Req_Filtes, Req_Prompts)" +
"VALUES (#reqNUM,#reqName,#reqDescrip,#reqcolumns,#reqfilters,#reqprompts)"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text)
cmd.Parameters.AddWithValue("#reqDate", DateTime.Today)
cmd.Parameters.AddWithValue("#reqExpecDate", DateTime.Parse(txtbxExpecDate.Text).ToShortDateString())
cmd.Parameters.AddWithValue("#reqNUM", txtRep_NUM.Text)
cmd.Parameters.AddWithValue("#reqName", txtRep_Name.Text)
cmd.Parameters.AddWithValue("#reqDescrip", txtbxRep_Desc.Text)
cmd.Parameters.AddWithValue("#reqcolumns", txtbxColReq.Text)
cmd.Parameters.AddWithValue("#reqfilters", txtbxFilReq.Text)
cmd.Parameters.AddWithValue("#reqprompts", txtbxPromReq.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Immediately after you ExecuteNonQuery() your INSERT INTO ReportReq ... statement you need to run a
SELECT ##IDENTITY
query and retrieve its result, like this
cmd.ExecuteNonQuery() ' your existing statement to run INSERT INTO ReportReq
cmd.CommandText = "SELECT ##IDENTITY"
Dim newAutoNumberValue As Integer = cmd.ExecuteScalar()

Syntax error in query. Incomplete query clause in Max statement inside a function

I am trying to simply connect to a database. But the problem arises in the concatenation part of the Sql query.
When I do:
cmd = New OleDbCommand("Select max(ID) from Table1", con)
There is no error but when I do
cmd = New OleDbCommand("Select max(ID) from'" & tablename & "'", con)
The vb.net error comes: Syntax error in query. Incomplete query clause.
Here is the full code
Function Get_Max(ByVal Get_Table_Name As String)
Dim tablename As String = Get_Table_Name
Dim found_max As Integer
Call connect()
con.Open()
cmd = New OleDbCommand("Select max(ID) from'" & tablename & "'", con)
dr = cmd.ExecuteReader
While dr.Read
found_max = dr(0)
End While
con.Close()
MsgBox(found_max)
Return found_max
End Function
Do not put single quotes around the variable tablename
cmd = New OleDbCommand("Select max(ID) from " & tablename, con)
Otherwise the tablename variable becomes a literal string and, from the database point of view you are requesting the MAX(ID) of the string 'Table1'.
A part from this you should be absolutely sure about the value of the variable tablename.
Do not allow the end user to directly type this value (at least let him choose between a list of predefined names).
This kind of code is very weak and open to Sql Injections.
And, as other answers have already outlined, a couple of Square Brackets around the table name are required if one or more of your tables contains a space or have the same name as a reserved keyword
cmd = New OleDbCommand("Select max(ID) from [" & tablename & "]", con)
change this line
cmd = New OleDbCommand("Select max(ID) from " & tablename & "", con)
to this
cmd = New OleDbCommand("Select max(ID) from " & tablename, con)
you just missed a space and remove the "'"
You are adding in additional quote characters. Your initial string
cmd = New OleDbCommand("Select max(ID) from'" & tablename & "'", con)
is evaluating to
cmd = New OleDbCommand("Select max(ID) from'Table1'", con)
Instead, you should probably be using:
cmd = New OleDbCommand("Select max(ID) from [" & tablename & "]", con)
The [ and ] give you additional protection against reserved words matching table names, although not SQL query injection, to which this code may still be vulnerable.