I need to insert a row into the Access table. I have been getting
object reference not set to instance of an object
My code is:
Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim strconstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb"
Dim objcon As OleDb.OleDbConnection
objcon = New OleDb.OleDbConnection(strconstring)
Dim objcommand As OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Try
objcon.Open()
Dim command As String
command = "insert into Artists(Artist, Company, Sales )" _
& " values('" & ArtistBox.Text & "', '" _
& TextBox2.Text & "', " & TextBox3.Text & ")"
objcommand = New OleDb.OleDbCommand(command, objcon)
da.InsertCommand.CommandText = command
da.InsertCommand.ExecuteNonQuery()
Catch exceptionobject As Exception
MessageBox.Show(exceptionobject.Message)
Finally
objcon.Close()
End Try
End Sub
Your connection string is a bit of a mess, so that may be causing the problem. Use EITHER...
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb;
...OR...
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb;
Related
This is my problem:
When I click update button, I don't know how to fix this error:
My Error Message is:
"Error: syntax error in union query"
This is my code:
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Try
Dim cmd As OleDbCommand
Dim sql As String
sql = "(UPDATE tblUsers SET Username = '" & txtUserName.Text & "', Password = '" & txtUserPassword.Text &
"', Usertype = '" & cbousertype.Text & "', WHERE UserID = '" & txtUserID.Text & "');"
cmd = New OleDbCommand(sql, Conn)
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Error: " & ex.Message)
End Try
End Sub
Is it wrong?
Now my problem has been solved thank you very much
i changed my code to use a parameters and then it work
Now my code is :
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
TestConnection()
Dim cmd As OleDbCommand
Dim sql As String
sql = "UPDATE tblUsers SET Username=?, [Password]=?, Usertype=? where UserID=?"
cmd = New OleDbCommand(sql, Conn)
cmd.Parameters.AddWithValue("#p1", txtUserName.Text)
cmd.Parameters.AddWithValue("#p2", txtUserPassword.Text)
cmd.Parameters.AddWithValue("#p3", cbousertype.Text)
cmd.Parameters.AddWithValue("#p4", txtUserID.Text)
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Updated", MsgBoxStyle.Information, "Updated")
ShowUser()
End Sub
I'm trying to search a keyword in the SQL Server db from Textbox1 and printing the corresponding details in other TextBoxes.
While running the below code, it shows it is unable to convert the DateTime and Integer value into String to display it in the TextBoxes.
Also there is another end of statement expected error in the command.Parameter line:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Server= DESKTOP-STMQUHM; Database = HospitalDB;Trusted_Connection=True")
Dim command As New SqlCommand("select * from Medicines where MedicineName ='" & TextBox1.Text & "' ", connection)
command.Parameters.Add("#Textbox1",SqlDbType.Text)Value=TextBox1.Text 'Another error
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
If table.Rows.Count() > 0 Then
TextBox1.Text = table.Rows(0)(1).ToString
TextBox2.Text = table.Rows(0)(2).ToString
TextBox3.Text = table.Rows(0)(3).ToString
TextBox4.Text = table.Rows(0)(4).ToString
Else
MessageBox.Show("NO DATA FOUND!!")
End If
End Sub
Try to change this:
Dim command As New SqlCommand("select * from Medicines where MedicineName ='" & TextBox1.Text & "' ", connection)
command.Parameters.Add("#Textbox1",SqlDbType.Text)Value=TextBox1.Text
Into this:
Dim command As New SqlCommand("select * from Medicines where MedicineName = #MedicineName", connection)
command.Parameters.Add("#MedicineName",SqlDbType.Text).Value=TextBox1.Text
This is because you have not declared the parameter name into your original SQL string, then on the second line of your code, before Value, you're missing a dot.
i am trying to insert my listview items into my MS access database.
here is the code:
Public newConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Inbox.Accdb;Persist Security Info=False;"
Private Sub btnNewSMS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewSMS.Click
cn.ConnectionString = newConn
If cn.State = ConnectionState.Closed Then
cn.Open()
For x = 0 To ListView2.Items.Count - 1
Dim sqlQuery As String = "INSERT INTO InboxTable (Contact_Name,Contact_Number,DateAndTime,Message) Values ('" & ListView2.Items(x).SubItems(0).Text & "', '" & ListView1.Items(x).SubItems(1).Text & "','" & ListView1.Items(x).SubItems(2).Text & "','" & ListView1.Items(x).SubItems(3).Text & ")"
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = cn
.ExecuteNonQuery()
End With
MsgBox("Messages Saved")
ListView2.Items.Clear()
'End With
Next
End If
cn.Close()
End Sub
my error is:
Value of '0' is not valid for 'index'
my problem is in inserting the values. Please Help me... thanks everyone - Chris
'Try this..
Public newConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Inbox.Accdb;Persist Security Info=False;"
Private Sub btnNewSMS_Click(sender As Object, e As EventArgs) Handles btnNewSMS.Click
For Each x As ListViewItem In ListView2.Items
Dim sqlQuery As String = "INSERT INTO InboxTable (Contact_Name,Contact_Number,DateAndTime,Message) Values ('" & _
x.SubItems(0).Text & "', '" & _
x.SubItems(1).Text & "','" & _
x.SubItems(2).Text & "','" & _
x.SubItems(3).Text & "')"
'Add also the last single qoute before the parenthesis ^_^
'to make sure the query works..
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = cn
.ExecuteNonQuery()
End With
MsgBox("Messages Saved")
ListView2.Items.Clear()
End With
Next
End Sub
Use this code for more than one form’s
DataTransfer.vb
Public Class DataTransfer
Public Sub ListToData(ByVal strcon As String, ByVal strcmd As String, ByVal listview As ListView)
Dim i As Integer = 0
Dim k As Integer = 0
Dim item As New ListViewItem
Dim con As New System.Data.OleDb.OleDbConnection(strcon)
Dim cmd As New System.Data.OleDb.OleDbCommand(strcmd, con)
Try
MessageBox.Show(listview.Items.Count)
While i < listview.Items.Count
item = New ListViewItem()
item = listview.Items(i).Clone
itemToString(item, strcmd)
con.Open()
cmd.CommandText = strcmd
cmd.ExecuteNonQuery()
MessageBox.Show("saved")
i += 1
End While
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
MessageBox.Show(strcmd)
End Sub
Private Sub itemToString(ByVal item As ListViewItem, ByRef strcmd As String)
Dim k As Integer = 1
strcmd += "VALUES ("
strcmd += "'" & item.Text & "'"
MessageBox.Show("subitems" + item.SubItems.Count.ToString)
While k < item.SubItems.Count
strcmd += ",'" & item.SubItems(k).Text & "'"
k += 1
End While
strcmd += ")"
End Sub
End Class
Form1.vb
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim datatransfer As New DataTransfer
Dim con As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\schoolDB.accdb"
Dim cmd As String = "INSERT INTO Stu_Info (C_ID, ADM_No, S_Name)"
datatransfer.ListToData(con, cmd, ListView1)
End Sub
End Class
I have a forum where I want the user to type a profile name and then click Add and then it will add what they typed in the text box the the ProfileName field in my table. When I click the Add button, it comes up with an error that says An unhandled exception of type System.Data.OleDb.OleDbException occurred in system.data.dll. Here is my code:
Private Sub RefreshData()
Dim cnn As New OleDb.OleDbConnection
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT id AS [ID], " & _
"ProfileName AS [Name] " & _
" FROM Profile ORDER BY id", cnn)
Dim dt As New DataTable
da.Fill(dt)
cnn.Close()
Me.dgvData.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (TextBox1.Text = "") Then
MsgBox("Please enter a profile name.")
Else
Dim cnn As New OleDb.OleDbConnection("Provider=Microsof… Source=c:\Data\Database.mdb ;Extended Properties=Paradox 5.x;")
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Profile(ProfileName) " & _
"VALUES (" & Me.TextBox1.Text & "')"
cmd.ExecuteNonQuery()
cnn.Close()
Dim oForm As addsnake
oForm = New addsnake
oForm.Show()
oForm = Nothing
Me.Close()
End If
End Sub
Without further information I suggest that:
You don't need to give id an alias of ID:
SELECT id AS [ID]
you might still enclose it in square-brackets though, if you like:
SELECT [id]
You are missing an apostrophe in the following line:
"VALUES (" & Me.TextBox1.Text & "')"
Also check your connection string at connectionstrings.com
How can you add data in a window form to a sql database in visual studio 2005?
I'm facing problems while saving.
Public Class Staff
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim dr1 As SqlDataReader
Dim ra As Integer
Private Sub cmdsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdsave.Click
myconnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=medisam")
myconnection.Open()
mycommand = New SqlCommand("insert into staff([FirstName],[LastName],[Address],[DOB], [TelephoneNum], [DateJoinIn], [HighestQualifi], [AppointedAs], [Salary]) VALUES ('" & txtfname.Text & "','" & txtlname.Text & "','" & txtaddress.Text & "','" & txtdob.Text & "','" & txttelephone.Text & "','" & txthqualifi.Text & "','" & ComboBox1.SelectedValue & "','" & txtsalary.Text & "')", myconnection)
mycommand.ExecuteNonQuery()
myconnection.Close()
End Sub
End Class
Well, at first glance, I can see a missing value in your query text:
I can count 9 fields and only 8 values... but this could be only an typing error.
More serious instead is the lack of parameter use. As #slaks pointed in its comment, this kind of code leads to Sql Injection Attacks. Also, you are passing all values as strings. I doubt that your [staff] table contains only text fields (DOB, DateJoinIn, AppointedAs). If it does, your schema design is horribly broken. The parameters could also help avoid this kind of error. Finally, connecting with the sa account will cause your dba to hunt you down and beat you to within an inch of your life.
Please rewrite your method in this way:
Private Sub cmdsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdsave.Click
Using (myconnection as SqlConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=medisam"))
myconnection.Open()
mycommand = New SqlCommand("insert into staff([FirstName],[LastName],[Address],[DOB], " & _
"[TelephoneNum], [DateJoinIn], [HighestQualifi], [AppointedAs], [Salary]) " & _
"VALUES (#first, #last, #address, #dob, #tel, #dateJ, #highQ, #appointed, #sal)", myconnection)
mycommand.Parameters.AddWithValue("#first", txtfname.Text)
mycommand.Parameters.AddWithValue("#last", txtlname.Text)
mycommand.Parameters.AddWithValue("#address", txtaddress.Text)
mycommand.Parameters.AddWithValue("#dob",txtdob.Text) ' if this is a date, need to convert
mycommand.Parameters.AddWithValue("#tel",txttelephone.Text)
mycommand.Parameters.AddWithValue("#dateJ", txt??? Missing ????)
mycommand.Parameters.AddWithValue("#highQ",txthqualifi.Text)
mycommand.Parameters.AddWithValue("#appointed",ComboBox1.SelectedValue) ' need to convert ???
mycommand.Parameters.AddWithValue("#sal",txtsalary.Text) ' need to convert ???
mycommand.ExecuteNonQuery()
End Using
End Sub