Cannot Add new row to database with DataAdapter.insertCommand vb.net - vb.net

I try to add new record to the database with command DataAdapter.InsertCommand. But I don't know why It doesn't insert new record to database
Here is my code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\1_Project\Project_of_VB_Net\AccessDatabase\StudentDatabase.accdb"
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO StudentData(StudentID) VALUES (#studentid)"
cmd.Parameters.AddWithValue("#studentid", "123")
Try
cnn.Open()
da.InsertCommand = cmd
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
cnn.Close()
End Try
End Sub
Please help me find out what's wrong with it?

I'm all in favor of using what works and I see the solution above works. The advantage of using a dataadapter however, is that it wraps all the sql commands needed for the CRUD operations of the datatable. You can configure your own commands or let visual studio configure them automatically by using a sqlcommandbuilder. Then once you have the adapter configured all you need to do is something like this
Dim myds As New DataSet()
Dim mytable as New datatable()
myds.Tables.Add(mytable)
Dim myconstr As String = "ConnectionStringtoDataBase"
Dim myconn As New SqlConnection(myconstr)
Dim da as new SqlDataAdapter( “SELECT * FROM StudentTable”,cnn)
Dim mycb As New SqlCommandBuilder(da)
da.Fill(mytable)
Dim myrow As DataRow = mytable.NewRow()
myrow("ID") = "thestudentid"
myrow("StudentName") = "John doe"
myrow("StudentID") = 12345
myrow("StudentClass") = "VB 101"
mytable.Rows.Add(myrow)
da.Update(mytable)
The CommandBuilder will automatically add insert, update and delete commands to the dataadapter (if your select command is one table only, otherwise you'll have to configure it manually).

Related

textbox AutoComplete not working after a search query

Hello there I am quite new to windows form programming, and my project requires me to do a search query on my database. I would like the option for the names that can be currently searched to be displayed when typing, however, after pressing the search button the autocomplete no longer displays when I try to look for another attribute. https://i.stack.imgur.com/Wytdy.png , https://i.stack.imgur.com/Qjy5q.png
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
MaxRows = ds.Tables("customers").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customers;"
dgvCustomerInfo.DataSource = display(msSQL, "customers")
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT DISTINCT fname FROM customers"
End With
da.SelectCommand = cmd
da.Fill(dt)
Dim r As DataRow
txtSearchName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
txtSearchName.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()
I believe your problems stem from the AutoCompleteMode. Suggest and SuggestAppend seem to fill in the text box as expected. Append seem to do nothing. I don't think this is working as intended.
I tested with a little database I have. It is Sql Server but should work the same for Sqlite. I used a bit of Linq magic to get the AutoCompleteCustomSource. A few other changes... Using...End Using blocks ensure that database objects are closed and disposed. You don't need a DataAdapter, just a DataTable and Command.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataForTextBox()
Dim strArray = dt.AsEnumerable().[Select](Function(x) x.Field(Of String)("Name")).ToArray()
TextBox5.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim MySource As New AutoCompleteStringCollection()
MySource.AddRange(strArray)
TextBox5.AutoCompleteCustomSource = MySource
TextBox5.AutoCompleteMode = AutoCompleteMode.SuggestAppend
End Sub
Private Function GetDataForTextBox() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Distinct Name From Coffees", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetSearchResults(TextBox5.Text)
DataGridView1.DataSource = dt
End Sub
Private Function GetSearchResults(name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select * From Coffees Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function

Differences in populate a DataGridView using SQLiteDataAdapter vs. SQLiteDataReader

For populate a DataGridView with data from a SQLite DataBase I think the easy way is using SQLiteDataAdapter, populate a Table and make the Table the DataSource of the DataGridView, something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles cdmDataTable.Click
Dim conn = New SQLiteConnection("Data Source=MyDataBase.sqlite;Version=3")
Try
Using (conn)
conn.Open()
Dim sql = "SELECT * FROM users"
Dim cmdDataGrid As SQLiteCommand = New SQLiteCommand(sql, conn)
Dim da As New SQLiteDataAdapter
da.SelectCommand = cmdDataGrid
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
Dim readerDataGrid As SQLiteDataReader = cmdDataGrid.ExecuteReader()
End Using
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Is there any advantage using SQLiteDataReader instead of SQLiteDataAdapter?
Data adapter is a higher level component that connects a DataTable to the underlying database. It can fill the DataTable and it can sync the changes on the DataTable back to the database. The DataAdapter uses a DataReader internally to read the data from the table.
There is no significant advantage using a DataReader over a DataAdapter to fill a DataTable.

Updating a remote Access server

In the creation of my program, i have found it will be more reliable to supply a local database with the package, rather then connecting to the remote DB for each instance.
Below is my idea on how to do it, however i wish for it to happen automatically for each distinct host that it finds, rather than selecting each member and pressing the button. This is something that i do not know how to achieve.
Imports System.Data.OleDb
Public Class Form1
Dim con as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='.\localDB.accdb'")
Dim rem as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='\\server\remote.accdb'")
dim da as new oledbdataadaptor
dim dt as new datatable
dim dt2 as new datatable
Dim Str as string
Dim cmd as new oledbcommand(str, con)
Private Sub Form1_load
con.open()
da.SelectCommand = New OleDbCommand("select distinct Host from Logs")
da.fill(dt)
con.close
Combobox1.datasource = dt
Combobox1.displaymember = "Host"
End Sub
Private Sub button1_click
con.open()
Dim cmd As New OleDbCommand("select * from local where host=#host;", con)
cmd.parameters.addwithvalue("#host", combobox1.text.tostring)
da.fill(dt2)
con.close()
rem.open()
Dim cmd1 As New OleDbCommand("update remote set col1=#col1 where ID=#ID;", con)
cmd1.parameters.addwithvalue("#col1", dt2.rows(0).item(1).tostring)
cmd1.parameters.addwithvalue("#ID", dt2.rows(0).item(0).tostring)
rem.close()
End Sub
End Class
Any idea's would be appreciated.
*As a note, i realise that JET offers the sync ability however the database is required to be in the 2007-10 format, so ACE is the only option.
First of all OleDbCommand does not accept named parameters, so you need to reference them with ? and pass the parameters in the same order that they appear.
Dim cmd As New OleDbCommand("select * from local where host = ?", con)
cmd.parameters.Add(combobox1.Text.ToString)
Once done, you'll need to fill the DataSet with the results of the SQL sentence
Dim DA As New OleDbDataAdapter(cmd)
Dim DS As New DataSet
DA.Fill(DS, "hosts")
UPDATE
In order to have an equivalent code as yours, I would do something like this
Imports System.Data.OleDb
Public Class Form1
Dim con as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='.\localDB.accdb'")
Dim rem as oledbconnection = new oledbconnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='\\server\remote.accdb'")
dim dt as New DataTable
Dim Str as String
Dim cmd as New OleDbCommand(str, con)
Private Sub Form1_load
con.open()
da.SelectCommand = New OleDbCommand("select distinct Host from Logs")
da.fill(dt)
con.close
For Each DR as DataRow In DT.Rows
con.open()
Dim cmd As New OleDbCommand("select * from local where host= ? ", con)
cmd.Parameters.Add(DR.Item(0))
Dim DA As New SqlClient.SqlDataAdapter(cmd)
Dim DS As New DataSet
da.Fill(DS,"hosts")
con.close()
rem.open()
Dim cmd As New OleDbCommand("update remote set col1=? where ID=?", rem)
cmd.Parameters.Add(DS.Tables("hosts").Rows(0).Item(1).ToString)
cmd.Parameters.Add(DS.Tables("hosts").Rows(0).Item(0).ToString)
cmd.ExecuteNonQuery()
rem.close()
Next
End Sub
End Class

“The ConnectionString property has not been initialized” error in VB.NET

Every time I tried to connect to the database it give me this error "The ConnectionString property has not been initialized"
How can i avoid this error and make it work?
Here are my codes:
Imports System.Data.OleDb
Public Class frmLoginPage
Dim con As New OleDbConnection
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("Select*from tblPassword", con)
da.Fill(dt)
Dim newRow As DataRow = dt.NewRow
With newRow
If .Item("Username") = txtUsername.Text And .Item("Password") = txtPassword.Text Then frmMainMenu.ShowDialog() Else MsgBox("The username or password you entered was incorrect, please try again!", MsgBoxStyle.Critical, "Information")
End With
End Sub
You have instantiated an OleDbConnection object, but you haven't set the connectionstring property so it doesn't know where it should connect to. You also haven't opened it. Your code should look something like:
Dim myConnection As OleDbConnection = New OleDbConnection()
myConnection.ConnectionString = myConnectionString
myConnection.Open()
' execute queries, etc
myConnection.Close()
This Problem Occurs when you donot consider making a new connection
The solution is very simple, all you have to do is to make
Dim conString as string = "Your connection string here"
Dim con As new OleDbConnection
con.connectionSting= ConSting
con.open()
'now simply write the query you want to be executed
'At the end write
con.close()
this will solve your problem.
if it doesn't solve your problem post reply I will try to solve it.
You never assigned your connection string to the connection object, just like the error is saying.
Insert a line setting the connection string before con.open.
Con.connectionstring = connection
Con.Open()
Or better yet, change your using statement as follows
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Using Con As New SqlConnection(connection)

Display SQL query result on VB form

I am facing a problem displaying the result of my "select *" query on the form . Here is my code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
myconnection = New SqlConnection("server=PARTH-PC\SQLEXPRESS;uid=sa;pwd=parth;database=college")
myconnection.Open()
mycommand = New SqlCommand("SELECT * from [demo3]",myconnection)
Dim mySqlDataAdapter As New SqlDataAdapter(mycommand)
Dim mydsStudent As New DataSet()
DataGridView2.DataSource = mydsStudent
Me.Controls.Add(DataGridView2)
ra = mycommand.ExecuteNonQuery()
MessageBox.Show("Data displayed" & ra)
myconnection.Close()
End Sub
But when I write this code and run my form I am not able to see any records present in my database tables being displayed on my form. I have inserted a DataGridView on my form . What changes should I do to my code ? Can Anyone help me ?
Thanks in advance
When you are working with a DataAdapter, you need to call the Fill() method for it to fill a DataSet/DataTable. After you initialize the DataSet, make this call:
mySqlDataAdapter.Fill(mydsStudent)
Also, take out your ExecuteNonQuery() call.
EDIT: Try something like this.
Dim myconn As New SqlConnection(yourConnectionStringHere)
Dim myTable As New DataTable()
Dim myCmd As New SqlCommand()
myCmd.Connection = myconn
myCmd.CommandText = "select * from demo3"
Dim myAdapater As New SqlDataAdapter(myCmd)
myAdapter.Fill(myTable)
DataGridView2.DataSource = myTable