How to fix the connectionstring property has not been initialized - vb.net

I am trying to create a user and insert the data into a MS Access database, but I get an error:
The connectionString property has not been initialized
whenever I click on the button.
I have tried all possible codes on Connection string but the challenge still persist.
Try
Dim sqlconn As New OleDb.OleDbConnection
Dim sqlquery As New OleDb.OleDbCommand
Dim connString As String
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PavilionDB.mdb"
sqlquery.Connection = sqlconn
con = New OleDbConnection(conString)
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand(sql, con)
sqlquery.CommandText = "INSERT INTO member(mmbr_id, name, gender, address, phone, join_date, acc_no) VALUES (#txtNewID, #txtName, #txtGender, #txtAddress, #txtPhone, #txtPhone, #)txtAccNo"
sqlquery.Parameters.AddWithValue("New ID", txtNewID.ToString)
sqlquery.Parameters.AddWithValue("Name", txtName.ToString)
sqlquery.Parameters.AddWithValue("Gender", txtGender.ToString)
sqlquery.Parameters.AddWithValue("Address", txtAddress.ToString)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataTable
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "con")
Return
sqlquery.ExecuteNonQuery()
sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

That code really is a mess. It should be reduced to this and that will fix your issue:
Try
Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PavilionDB.mdb"),
command As New OleDbCommand("INSERT INTO member (mmbr_id, name, gender, address, phone, join_date, acc_no) VALUES (#mmbr_id, #name, #gender, #address, #phone, #join_date, #acc_no)", connection)
With command.Parameters
.AddWithValue("#mmbr_id", txtNewID.Text)
.AddWithValue("#name", txtName.Text)
.AddWithValue("#gender", txtGender.Text)
.AddWithValue("#address", txtAddress.Text)
'Set other parameters here.
End With
connection.Open()
command.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Ideally, you would be using Add rather than AddWithValue too, but that's another conversation.

Here is simple code for what you mostly asked for, in addition to the whole open source on this link:
enter link description here
Here is the tested code:
Private Sub BtnAddNewRec_Click(sender As Object, e As EventArgs) Handles BtnAddNewRec.Click
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\db1.mdb"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Tbl1 (mmbr_id, name, gender, address) VALUES (#txtNewID, #txtName, #txtGender, #txtAddress)"
cmd.Parameters.AddWithValue("#txtNewID", txtNewID.Text)
cmd.Parameters.AddWithValue("#txtName", txtName.Text)
cmd.Parameters.AddWithValue("#txtGender", txtGender.Text)
cmd.Parameters.AddWithValue("#txtAddress", txtAddress.Text)
cmd.ExecuteNonQuery()
MsgBox("Record Added Successfully!")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
End Sub
I hope this helps:

The trouble here is that you have 2 commands in your code, namely cmd and sqlquery. You define sqlquery at the beginning of the code, then initialize cmd with the connection and a SQL variable that I cannot determine the source of.
What you need to do is redo this part and get remove the extra references that seem to be the source of the problem. Consider the following...
Try
Dim conString As String
Dim text = "INSERT INTO member(mmbr_id, name, gender, address, phone, join_date, acc_no) VALUES (#txtNewID, #txtName, #txtGender, #txtAddress, #txtPhone, #txtPhone, #)txtAccNo"
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PavilionDB.mdb"
Using sqlCon = New OleDbConnection(conString), sqlCmd = New OleDbCommand(text, sqlCon)
With sqlCmd.Parameters
.AddWithValue("New ID", 234234)
.AddWithValue("Name", "Fabulous")
.AddWithValue("Gender", "Male")
.AddWithValue("Address", "127.0.0.1")
End With
sqlCon.Open()
sqlCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
I couldn't tell whether txtNewID and the other similarly named variables are text boxes or not. If they are text boxes, you need the .Text property which gets the content in a string. You'll need to replace the literals I used in my test environment to get to it.
Ensure everything, including your connection string and query are correct for this to run smoothly. In your current case, you are getting the connection string related error because you are attempting to execute the query on a connection you didn't associate with the connection.

Related

Insert text into MS access cells

i am begginer in visual basic and i want to insert text into cells in column in MS access but i doesn't find, how could i do that.
Here is code i tried:
Private Sub UpdateDataBase2()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "F:\Test Database\Database.accdb"
conString = provider & datafile
myConnection.ConnectionString = conString
myConnection.Open()
Dim str As String
str = "Insert into TABLA([LABELS]) Values (?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
Select Case panelCount
Case 1
' TextBox1.Text = cmd.Add("LABELS").Rows(0).Item(1).ToString()
Case 2
' str = "Insert into TABLA([LABELS]) Values (?)"
'cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
End Select
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Close()
End Sub
In this application, i made a dynamics panels and labels.(dynamics is for me generated in code)
panelcount is variable which saves to another MS acces database count of dynamics panels. I want to save text from labels to database systematically(it means: text from label 1 insert to cell 1.), but every code i tried was not function for me.
I know i have to use loop, but first i want to try if code works.
Sorry for my english.
Any solution?
Database objects like Connection and Command should be declared in the method where they are used so they can be disposed.
Use Using...End Using blocks to ensure that your database objects are closed and disposed even if there is an error.
Insert creates a new record. If you want to Update an existing record you will need the primary key value for the record you want to update.
Dim Str = Update TABLA Set [LABELS] = ? Where ID = ?
Then you will need a second parameter.
cmd.Parameters.Add("ID", OleDbType.Integer).Value = intID
You will need to declare and provide a value for intID.
Don't show a message box while a connection is open.
Private Sub OPCode()
Try
Dim Str = "Insert into TABLA([LABELS]) Values (?)"
Dim ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"
Using myConnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Str, myConnection)
cmd.Parameters.Add("LABELS", OleDbType.VarChar).Value = TextBox1.Text
myConnection.Open()
cmd.ExecuteNonQuery()
End Using 'Closes and disposes the connection and disposes the command
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

could not update currently locked vb.net error

I want to Insert 2 different data in 2 different table of ms-access.
And it shows this error.
I have a code like this:
try
dim sql1,sql2 as string
sql1 = "INSERT INTO table1(something)VALUES(something)"
cmd = new oledbcommand(sql1, connection)
cmd.executenoquery()
sql2 = "INSERT INTO table2(something)VALUES(something)"
cmd2 = new oledbcommand(sql2, connection)
cmd2.executenoquery()
catch ex as exception
msgbox(ex.tostring())
(where these cmd1,cmd2 are defined in controlModule.)
so,what should I do ?
Any help is appreciated. Thank You
I think closing the connection fixes the issue, best by using the Using-statement:
try
Using con As OleDbConnection = GetConnection() ' or New OlebConnection(...)
Using cmd = con.CreateCommand()
cmd.CommandText = "INSERT INTO table1(something)VALUES(#something)"
cmd.Parameters.AddWithValue("#something", something)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Using con As OleDbConnection = GetConnection()
Using cmd = con.CreateCommand()
cmd.CommandText = "INSERT INTO table2(something)VALUES(#something)"
cmd.Parameters.AddWithValue("#something", something)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
msgbox(ex.tostring())
End Try
This is a concurrency issue. Because some other part of your code or MS Access itself accesses the database at the same time.
The fact is that you're not closing the connection after it's use. So the 2nd call should fail with that exception. Instead, you should wrap your disposables - e.g. the OleDbConnection, commands, etc. - in a using statement. That way, the connection will be closed, even if an exception occur:
Using con As New OleDbConnection, cmd1 As OleDbCommand = con.CreateCommand, cmd2 As OleDbCommand = con.CreateCommand()
cmd1.CommandText = "INSERT INTO table1(something)VALUES(something)"
cmd1.ExecuteNonQuery()
cmd2.CommandText = "INSERT INTO table2(something)VALUES(something)"
cmd2.ExecuteNonQuery()
End Using

Updating Table from vb to Access using ConnectionString

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Try
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb"
con.Open()
cmd.Connection = con
cmd.Connection = con
cmd.CommandText = ("UPDATE User_Name SET User_Name = #User_Name, Game_Name = #Game_Name, Score = #Score, Time/Date = #Time/Date")
cmd.Parameters.Add("#User_Name", SqlDbType.VarChar).Value = txtUser.Text
cmd.Parameters.Add("#Game_Name", SqlDbType.VarChar).Value = txtGame.Text
cmd.Parameters.Add("#Score", SqlDbType.VarChar).Value = txtScore.Text
cmd.Parameters.Add("#Time/Date", SqlDbType.DateTime).Value = txtDate.Text
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
con.Close()
Catch ex As System.Exception
MessageBox.Show("Data Update has failed")
End Try
End Sub
The code is giving an Exception is an ArgumentException and also :Keyword not supported: 'provider'.
You are using Access. This database cannot be opened using the classes in System.Data.SqlClient. These classes are used when you want to connect to Sql Server, Sql Server Express or LocalDB.
If you want to reach an MSAccess database you need the classes in System.Data.OleDb and these classes are OleDbConnection, OleDbCommand etc...
Said that, please note, that your field Date/Time will give you headaches. Change that name or put always square brackets around it because the / will be interpreted as the division operator
So your code could be:
Using con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb")
Using cmd = new OleDbCommand("UPDATE User_Name
SET User_Name = #User_Name,
Game_Name = #Game_Name,
Score = #Score, [Time/Date] = #dt", con)
con.Open()
cmd.Parameters.Add("#User_Name", OleDbType.VarWChar).Value = txtUser.Text
cmd.Parameters.Add("#Game_Name", OleDbType.VarWChar).Value = txtGame.Text
cmd.Parameters.Add("#Score", OleDbType.VarWChar).Value = txtScore.Text
cmd.Parameters.Add("#dt", OleDbType.Date).Value = Convert.ToDateTime(txtDate.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
End Using
End Using
Other notes:
Disposable objects like the connection and the command should be enclosed inside a Using Statement to be disposed and closed as soon as possible.
The time field requires a DateTime value not a string. If you pass a string you will face the automatic conversion made by the engine and sometime the engine is unable to produce a valid date from your input string. This will raise another exception (DataType mismatch). Better check and convert the value before passing it.
Also the type of the parameters should be from the OleDbType enum.

What's wrong with this SQL Insert statement of mine?

I am trying to add a record to my table, however I'm getting an exception after it attempts to do so. I am able to open the connection successfully, (my first messagebox shows up) but after that I get the exception. Here's my code:
Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con = New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;")
Try
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (txtFirstName.Text, txtLastName.Text)"
cmd.Connection = con
con.Open()
MsgBox("Connection Open ! ")
cmd.ExecuteNonQuery()
MsgBox("Record inserted")
con.Close()
Catch ex As Exception
MsgBox("Error!")
End Try
End Sub
For future readers - Sql parameters will save a lot of your and your coworkers time.
Private Sub btnUpdateInfo_Click(sender As Object, e As EventArgs) Handles btnUpdateInfo.Click
Dim connString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=CISDB;Integrated Security=SSPI;"
Using connection As New SqlConnection(connString)
Using command As New SqlCommand(connection)
command.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES (#FirstName, #Lastname)"
Dim params As SqlParameter() =
{
New SqlParameter With { .ParameterName = "#FirstName", .SqlDbType.VarChar, .Value = txtFirstName.Text },
New SqlParameter With { .ParameterName = "#LastName", .SqlDbType.VarChar, .Value = txtLastName.Text },
}
command.Parameters.AddRange(params)
connection.Open()
command.ExecuteNonQuery()
' Inserted
End Using
End Using
End Sub
Same for try.. catch(as #Plutonix has noticed in the comments) - if you will get "real" exception you will find reason and solution much faster
You need to look at the exception message (ex.Message) see what the issue is...If you have an error similar to multipart identifier then try this query string instead of your current query string for a quick test.
cmd.CommandText = "INSERT INTO customers (FirstName,LastName) VALUES ('" & txtFirstName.Text & "', '" & txtLastName.Text & "')"
Check out parameterized query as previously indicated

Sql Adapter . How to update a DataTable with no primary keys

This table that I have has been created with no primary keys. There is a reason why its been created with no keys. It is something like a product and customer relationship table. So after the standard procedure of using SqlDataAdapter and DataSet along with DataTable to fill the DataGrid I have an error updating the changes.
I have been working on several forms using DataGrid' but they all work fine due to the fact the table have primary keys. I tried adding a composite key but it didn't work. So below is my code for theDataSet` and the update code which works for other forms.
The update codes:
cmdbuilder = New SqlCommandBuilder(adapter)
If primaryDS IsNot Nothing Then
primaryDS.GetChanges()
'update changes
adapter.Update(primaryDS)
MsgBox("Changes Done")
'refresh the grid
CMDrefresh()
End If
And here is the coding for the DataTable I tried adding 5 composite keys. So how do you update with this problem?
Try
myconnection = New SqlConnection(strConnection)
myconnection.Open()
adapter = New SqlDataAdapter(StrQuery, myconnection)
adoPrimaryRS = New DataSet
adapter.Fill(primaryDS)
Dim mainTable As DataTable = primaryDS.Tables(0)
DataGrid.AutoGenerateColumns = False
mainTable.PrimaryKey = New DataColumn() {mainTable.Columns(0), _
mainTable.Columns(1), _
mainTable.Columns(2), _
mainTable.Columns(3), _
mainTable.Columns(4)}
bndSrc.DataSource = mainTable
DataGrid.DataSource = bndSrc
gDB.Connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
So I decided to go on and answer my question. You cant use the code above to up but you can still insert the new rows. Since Dataset is a memory if the whole database was removed it would not be effect. So the answer to how to update a table with no primary key or composite keys it to trancute it then insert all rows from the Dataset Table in to it. Here is the Code for Trancute and The one below is to insert. With these the table gets new values. It works for me.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = strConnection
Dim strSql As String
'MsgBox(con.ConnectionString.ToString)
Try
con.Open()
cmd = New SqlCommand
cmd.Connection = con
strSql = "TRUNCATE TABLE Table1"
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
So here is The Insert code.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim strSql As String
con.ConnectionString = strConnection
For i As Integer = 0 To grdDataGrid.Rows.Count - 1
'MsgBox(con.ConnectionString.ToString)
con.Open()
cmd = New SqlCommand
cmd.Connection = con
Try
strSql = "INSERT INTO Table1 ( [one], [two], [three], [four], [five] )" +_
"VALUES (#one, #two, #three ,#four ,#five )"
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("#one", grdDataGrid.Rows(i).Cells(2).Value)
cmd.Parameters.AddWithValue("#two", grdDataGrid.Rows(i).Cells(0).Value)
cmd.Parameters.AddWithValue("#three", grdDataGrid.Rows(i).Cells(1).Value)
cmd.Parameters.AddWithValue("#four", grdDataGrid.Rows(i).Cells(3).Value)
cmd.Parameters.AddWithValue("#five", grdDataGrid.Rows(i).Cells(4).Value)
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
CMDrefresh()