Save to Oracle joined table using ID - vb.net

I save data from my form to Oracle DB table. Now I need to store data in joined table If my datagridview rows are not empty too, but this is where I got stucked. Joined table has ID_Table1_FK. Here is what I tried:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using con As OracleConnection = New OracleConnection("Data Source=MyDB;User Id=Lucky;Password=MyPassword;")
con.Open()
Using cmd As OracleCommand = New OracleCommand()
cmd.CommandText = "INSERT INTO Table1(ID_Table1_PK, E_NAME, E_SURNAME, DESCRIPTION, ENTRY_DATE)
VALUES(MyTable_seq.nextval,: ID,: Name,: Surname,: Desc,: Entry)"
cmd.Connection = con
cmd.Parameters.Add(New OracleParameter("ID", TxtName.Text))
cmd.Parameters.Add(New OracleParameter("Surname", TxtSurname.Text)
cmd.Parameters.Add(New OracleParameter("Desc", TxtDesc.Text))
cmd.Parameters.Add(New OracleParameter("Entry", DtpEntry.Value.ToShortTimeString))
cmd.ExecuteNonQuery()
End Using
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value = Nothing Then
Else
Using cmd1 As New OracleCommand()
cmd1.CommandText = "INSERT INTO Table_Join (ID_Table1, ID_Table_Join, ADDRESS, STATE)
VALUES(ID_Table1,: MyTable_seq.nextval,: address,: state)"
cmd1.Parameters.Add(New OracleParameter("ID_Table1", "WHAT SHOULD GO HERE??"))
cmd1.Parameters.Add(New OracleParameter("address", row.Cells(0).Value))
cmd1.Parameters.Add(New OracleParameter("state", row.Cells(1).Value))
cmd1.ExecuteNonQuery()
End Using
End If
End Using
End Sub
So basically I need any advice on how to pass same ID value to another (joined) table ?
P.S.: "MyTable_seq.nextval" is triggering automatic sequence number of records in DB.

Related

How to add edited date automatically to datetimepicker?

I want to make the time will fill automatically in Datetimepicker when I edit the price of my product. So, it can compare to the date of buying. So, I decided to use on_update_current_timestamp in MySQL database. My problem is how to convert a string into a date in Datagridview. Because when I was press the edit button it works but for the add button it's getting an error unable to convert MySQL date/time Is it have any solution to achieve my goal. If yes can u explain it. Thank u
Public Sub disp_data()
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "select * from produk"
cmd.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New MySqlDataAdapter(cmd)
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub tambah_btn_Click(sender As Object, e As EventArgs) Handles tambah_btn.Click
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = $"insert into produk values('{kode.Text}','{nama.Text}','{harga.Text}','{DateTimePicker1.Value.ToString("dd/mm/yyyy")}')"
cmd.ExecuteNonQuery()
kode.Text = ""
nama.Text = ""
harga.Text = ""
disp_data()
MessageBox.Show("Data berhasil ditambahkan")
End Sub
You can do it (and it's better) like this:
'...
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into produk values (#kode,#nama,#harga,#date)"
cmd.Parameters.AddWithValue("#kode", kode.Text)
cmd.Parameters.AddWithValue("#nama", nama.Text)
cmd.Parameters.AddWithValue("#harga", harga.Text)
cmd.Parameters.AddWithValue("#date", DateTimePicker1.Value.Date)
cmd.ExecuteNonQuery()
'...
let me know if it solves it, or if some adjustments are needed

Insert string into different tables based on combobox selection

1st off, my apologies if this question has been asked. I have looked but haven't found an exact answer to the problem I'm facing. Secondly, I must stress that, I am not a developer, I'm an engineer and only writing sowftware as a needs must situation.
I have a form which passes data to an access db (This works). However I need to update it so that it will pass the information to different tables within the same db based upon a selection in a combobox. For instance if combobox selection = X then insert into tableX, if combobox = Y then insert into tableY. Any and all help is appreciated.
I've tried using If statements in order to select the appropriate table, but this doesn't work.
Imports System.Data.OleDb
Public Class Form1
Public ds As New DataSet
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim rs As New resizer
Dim cmd As OleDbCommand
Private con As Object
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
provider = "Provider=Microsoft.Jet.OleDb.4.0;Data Source="
dataFile = "R:\Quality\NCR-Access_Database\NCRdb1.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = ""
If ComboBox2.SelectedText = "Assembly" Then
str = "Insert into [ASSEMBLYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Grinding" Then
str = "Insert into [GRINDINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Milling" Then
str = "Insert into [MILLINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Mill-Turn" Then
str = "Insert into [MILL-TURNtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Turning" Then
str = "Insert into [TURNINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Supplier" Then
str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Subcon" Then
str = "Insert into [PURCHASINGtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
ElseIf ComboBox2.SelectedText = "Quality" Then
str = "Insert into [QUALITYtbl]([NCR-No],[Week-No],[Part-No],[Drawing-Rev],[Description],[W/O-Number],[Operator-No],[Operation-No],[Machine-No],[Section],[Batch-Qty],[Reject_Qty],[Disposition],[Mat-Cost],[Standard-Cost],[Defect-Descripition],[Fault-Code],[Dept],[Root-Cause],[NCR-Pinksheet],[Action]) Values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
End If
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("NCR-No", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Week-No", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("Part-No", TextBox4.Text))
cmd.Parameters.Add(New OleDbParameter("Drawing_Rev", TextBox5.Text))
cmd.Parameters.Add(New OleDbParameter("Description", TextBox6.Text))
cmd.Parameters.Add(New OleDbParameter("W/O-No", TextBox7.Text))
cmd.Parameters.Add(New OleDbParameter("Operator-No", TextBox8.Text))
cmd.Parameters.Add(New OleDbParameter("Operation-No", TextBox9.Text))
cmd.Parameters.Add(New OleDbParameter("Machine-No", TextBox10.Text))
cmd.Parameters.Add(New OleDbParameter("Section", ComboBox2.Text))
cmd.Parameters.Add(New OleDbParameter("Batch-Qty", TextBox12.Text))
cmd.Parameters.Add(New OleDbParameter("Reject_Qty", TextBox13.Text))
cmd.Parameters.Add(New OleDbParameter("Disposition", TextBox14.Text))
cmd.Parameters.Add(New OleDbParameter("Mat-Cost", TextBox15.Text))
cmd.Parameters.Add(New OleDbParameter("Standard-Cost", TextBox16.Text))
cmd.Parameters.Add(New OleDbParameter("Defect-Description", RichTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Fault-Code", TextBox17.Text))
cmd.Parameters.Add(New OleDbParameter("Dept", TextBox18.Text))
cmd.Parameters.Add(New OleDbParameter("Root-Cause", RichTextBox2.Text))
cmd.Parameters.Add(New OleDbParameter("NCR-Pinksheet", ComboBox1.Text))
cmd.Parameters.Add(New OleDbParameter("Permanent-Action", RichTextBox3.Text))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TextBox1.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox3.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
ComboBox2.ResetText()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
RichTextBox1.Clear()
TextBox17.Clear()
TextBox18.Clear()
RichTextBox2.Clear()
ComboBox1.ResetText()
RichTextBox3.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
When submitting I get a dialog that states "Command text was not set for the command object". If i submit again, then I get an exception unhandled event in VS --- "System.InvalidOperationException: 'Not allowed to change the 'ConnectionString' property. The connection's current state is open.'"
use INSERT INTO syntax
INSERT INTO table-name (column-names)
VALUES (values)
SQL INSERT INTO with SELECT like this
INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
SELECT LEFT(ContactName, CHARINDEX(' ',ContactName) - 1),
SUBSTRING(ContactName, CHARINDEX(' ',ContactName) + 1, 100),
City, Country, Phone
FROM Supplier
WHERE CompanyName = 'casterx.co'

No value given for one or more required parameters vb.net oledb

Public Class ViewPhoneRecords
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim sqlquery As New OleDb.OleDbCommand
Dim con1 As New OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database.accdb")
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim sqlupdate As String
' Here we use the UPDATE Statement to update the information. To be sure we are
' updating the right record we also use the WHERE clause to be sureno information
' is added or changed in the other records
sqlupdate = "UPDATE PhoneRecords SET Forename=#Forename, Surname=#Surname, Address=#Address, PhoneModel=#PhoneModel, PhoneNumber=#PhoneNumber, Postcode=#Postcode WHERE IDNum='" & IDTextBox.Text & "'"
Dim cmd As New OleDbCommand(sqlupdate, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.Add(New OleDbParameter("#Forename", ForenameTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Surname", SurnameTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Address", AddressTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#PhoneModel", PhoneModelTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#PhoneNumber", PhoneNumberTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Postcode", PostcodeTextBox1.Text))
con1.Open()
cmd.ExecuteNonQuery()
MsgBox("Row(s) Inserted !! ") 'Displays message box informing the user that the database has been added to
con1.Close() 'Connection closed
Me.Refresh()
End Sub
This is supposed to update a selected record in a datagrid view. However, when I click the 'Save changes' button, an error is given; "No value given for one or more parameters." Any idea how to solve this?
Use cmd.Parameters.AddWithValue instead of cmd.Parameters.Add

give me a same code for deleting purposes..vb.net 2010 - closed

The code below is my code for saving records
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
'Change the following to your access database location
dataFile = "C:\Users\DELL\Downloads\WindowsApplication1\WindowsApplication1\Database1.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "insert into tblODR ([ID], [Office], [Elements], [Objectives], [Initiatves]) values (?, ?, ?, ?, ?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("ID", CType(IDTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Office", CType(OfficeTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Elements", CType(ElementsTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Objectives", CType(ObjectivesTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Initiatves", CType(InitiatvesTextBox.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Me.Validate()
Me.TblODRBindingSource.EndEdit()
Me.TblODRTableAdapter.Update(Me.Database1DataSet.tblODR)
Catch ex As Exception
MsgBox(ex.Message)
End Try
can anyone give me a same code BUT, for deleting purposes.. the code above adds a new record and shows instantly in the datagridview after adding it..(before i have code for adding purposes but it wont add instantly in the datagridview)..
What i want is, a code that when i delete a record using a textbox (i'm deleting records by inputting the ID Number of a record in a textbox)..the deleted record will show instantly after deleting it.. (my code as of now, when i delete a record, it would delete the record BUT i have to close the form and run the program again to show if the deleted record have been deleted)
You can use gridview1.refresh() method to refresh your grid on the delete button , so when delete common executes, it will refresh your gridview to update the new record use gridview1.update() to update the changes that you have made. Or you can also make your own method to refresh your gridview,here is the sample method to refresh the grid like this
Public Sub Gridrefresh(ByVal s As String, ByVal dgv As DataGridView)
Dim dt As New DataTable()
Dim cmd As New SqlCommand("select * from " + s + "", con.dbconnection())
cmd.CommandType = CommandType.Text
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
dgv.DataSource = dt
End Sub
here s represent name of your table , when you call this method u can use like this Gridrefresh("name of table ",datagridView1 name ), Hope this will help you

Creating new records in MSACCESS Table

I am attempting to create a new record from vb.net to an msaccess table, which i am able to do, but i have to add in the next consecutive ID number for it to actually save. For instance, if the next ID in the Access DB is 4, i have to type in 4 in the id textfield on my form. Code below:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sqlinsert As String
' We use the INSERT statement which tells our program to add the information
' from the Forms Text fields into the Databases columns.
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1, ID)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1, #ID)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
cmd.Parameters.Add(New OleDbParameter("#ID", Convert.ToInt32(TextBox5.Text)))
' This is what actually writes our changes to the DataBase.
' You have to open the connection, execute the commands and
' then close connection.
con1.Open()
cmd.ExecuteNonQuery()
con1.Close()
' This are subs in Module1, to clear all the TextBoxes on the form
' and refresh the DataGridView on the MainForm to show our new records.
ClearTextBox(Me)
RefreshDGV()
Me.Close()
End Sub
How can i tell textbox5 which is the ID field, to be the next number in the access db?
Open your Access database, show the structure of your table and change the ID field type from numeric to AutoNumber.
Now your code don't need to pass anything to Access because the number will be handled automatically from Access.
You could just add these lines to your code to get back the number assigned by Access to your field
Dim sqlinsert As String
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
con1.Open()
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
cmd.CommandText = "SELECT ##IDENTITY"
Dim assignedID = Convert.ToInt32(cmd.ExecuteScalar())
' Eventually
TextBox5.Text = assignedID.ToString
con1.Close()
......
See also
How to retrieve last autoincremented value in MS-Access like ##Identity in Sql Server
Create a SELECT statement to retrieve the Max number form the table and add one to it. I do not know VB.Net, so it should be something like.
maxQry = "SELECT Max(IDColumnName) As MaxID FROM theTableName;"
Dim cmd As New OleDbCommand(maxQry, con1)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
TextBox5.Text = dr("MaxID").ToString
End While
End If
Unless the field is an AutoNumber type you do not have to worry about it at all.