Saving data to access not working, despite no errors - vb.net

Hey I'm trying to use this code to save to my access database and although there are no errors and it says data saved, my access database doesn't receive the new data. What's wrong with it?
Private Sub savenew()
Dim conn As New OleDbConnection
conn = New OleDbConnection
dbprovider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source = FULL YUGIOH ACCESS DATABASE.accdb;"
conn.ConnectionString = dbprovider & dbsource
Dim reader As OleDbDataReader
Dim command As OleDbCommand
Try
conn.Open()
Dim query As String
query = "insert into item(name) values ('" & TextBox4.Text & "')"
command = New OleDbCommand(query, conn)
reader = command.ExecuteReader
MsgBox("data saved")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
(table in my database is called item, and column is called name.)

Related

How to set a Label.Text from a specific Column of an Access DB

I have an MS Access Contacts database file, with tables [Contact] and [Email].
Each contact can have multiple email addresses.
The Emails table has a "Primary" boolean Column, I am unchecking all other "Primary" cells associated with a specific contact, so each contact can only have 1 primary email address.
That is the value I am trying to retrieve from the database and display in Label1 on a DataRepeater control.
Here is my code trying to get the primary email address from the list of email addresses for a contact:
Try
Dim dbProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dbSource As String = Application.StartupPath & "\Data\Contacts.accdb"
Dim con As New OleDbConnection
Dim connString As String = dbProvider & dbSource
con.ConnectionString = connString
con.Open()
Dim cmd As New OleDbCommand("SELECT [E-mail Address] FROM Email WHERE ContactID='" & BindingNavigatorPositionItem.Text & "' AND Primary=True ", con)
Label1.Text = cmd.ExecuteScalar()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
The problem is the Label1.Text still shows Label1 when I run the program.
I know this is incorrect, but I am unable to find a solid example to pull a value from a specific cell and assign it to a label like I am trying to do.
Exception:
System.Data.OleDb.OleDbException (0x80040E07): Data type mismatch in
criteria expression. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult
hr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&
executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior
behavior, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior
behavior, String method) at
System.Data.OleDb.OleDbCommand.ExecuteScalar() at
Contacts_AccessDB.Form2.ContactBindingSource_CurrentItemChanged(Object
sender, EventArgs e) in C:\Users...\Contacts-AccessDB\Form2.vb:line
73
UPDATE:
This answer was provided in a comment, but is advised not to use because it is not using parameters:
Try
Dim dbProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dbSource As String = Application.StartupPath & "\Data\Contacts.accdb"
Dim con As New OleDbConnection
Dim connString As String = dbProvider & dbSource
con.ConnectionString = connString
con.Open()
Dim cmd As New OleDbCommand("SELECT [E-mail Address] FROM Email WHERE ContactID=" & BindingNavigatorPositionItem.Text & " AND Primary=True ", con)
Label1.Text = cmd.ExecuteScalar()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
And here is what I am currently doing:
Try
Dim dbProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dbSource As String = Application.StartupPath & "\Data\Contacts.accdb"
Dim connString As String = dbProvider & dbSource
Using conn As New OleDbConnection(connString)
Dim cmd As New OleDbCommand("SELECT [E-Mail Address] FROM Email WHERE ContactID=#ContactID AND Primary=True ", conn)
cmd.Parameters.Add("#ContactID", OleDbType.Integer).Value = CInt(BindingNavigatorPositionItem.Text.Trim)
conn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
reader.Read()
If reader.HasRows Then
Label1.Text = reader.Item(0).ToString()
End If
conn.Close()
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Try the following code. I changed your code to use parameters instead.
I did not check for errors in the code below but you should add some code to handle errors.
Using conn As New OleDbConnection( connString),
cmd As New OleDbCommand("SELECT [E-Mail Address] FROM Email WHERE ContactID=#ContactID AND Primary=True ", conn)
cmd.Parameters.Add("#ContactID", OleDbType.Integer).Value = CInt(BindingNavigatorPositionItem.Text.Trim)
conn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows AndAlso reader.Read()
Label1.Text = reader.Item(0).ToString()
End If
End Using

Load Report failed with crystal report

I got an error (load report failed) when trying to print crystal report in my vb.net application
but my problem is (this error hasn't occurred always) maybe after printing unknown number of reports, then once this error has occurred.
Here is my code:
Dim cmd As New OleDbCommand
Dim connp As New OleDbConnection
Dim da As New OleDbDataAdapter
Dim ds As New DataSet
Dim strsql As String
Dim strreprotname As String
Try
connp.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Application.StartupPath & "\report.mdb; Jet OLEDB:Database Password=KNOZ1003"
connp.Open()
ds.Reset()
strsql = "select * from tab3"
cmd.CommandText = strsql
cmd.Connection = connp
da.SelectCommand = cmd
da.Fill(ds)
strreprotname = "cashrpt"
Dim strreportpath As String = Application.StartupPath & "\Reports\" & strreprotname & ".rpt"
Dim rptdocument As New CrystalDecisions.CrystalReports.Engine.ReportDocument
Dim prnset As New Printing.PrinterSettings
Dim pg As New Printing.PageSettings
rptdocument.Load(strreportpath)
rptdocument.SetDataSource(ds.Tables(0))
rptdocument.SetDatabaseLogon("", "", "", Application.StartupPath + "\report.mdb")
prnset.PrinterName = cashprinter
rptdocument.PrintToPrinter(prnset, pg, False)
cmd.Dispose()
connp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Trouble loading data into textbox

Upon the click of a button, I want the program to load in details about the user (stored in an access database) into the textboxes.
This is what I have to far
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Administratot\Documents\RailwayDatabase2.accdb"
Dim MyConn As New OleDbConnection(connString)
Dim da As OleDbDataAdapter
Dim ds As DataSet
Try
MyConn.Open()
da = New OleDbDataAdapter("Select * from tbl_employees WHERE FirstName = """ & EmployeeLogin.usersname & """", MyConn)
ds = New DataSet
da.Fill(ds)
TextBox1.Text = ds.Tables("tbl_employees").Rows(0).Item(2)
MyConn.Close()
Catch ex As Exception
If MyConn.State <> ConnectionState.Closed Then MyConn.Close()
End Try
End Sub
any idea why this isn't working? thanks

Execute a SQL Stored Procedure and process the results [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In VB.NET, how do I do the following?
Execute a Stored Procedure
Read through the DataTable returned
At the top of your .vb file:
Imports System.data.sqlclient
Within your code:
'Setup SQL Command
Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("#Parameter1", sqlDBType.Int).value = Param_1_value
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'Fill the dataset
Dim DS as DataSet
adapter.Fill(ds)
connection.Close()
'Now, read through your data:
For Each DR as DataRow in DS.Tables(0).rows
Msgbox("The value in Column ""ColumnName1"": " & cstr(DR("ColumnName1")))
next
Now that the basics are out of the way,
I highly recommend abstracting the actual SqlCommand Execution out into a function.
Here is a generic function that I use, in some form, on various projects:
''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD)</summary>'''
''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."),'''
''' otherwise if there is just one token, it's a stored procedure command</param>''''
Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet
Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString
Dim ds As New DataSet()
Try
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers"
If CMD.CommandText.Contains(" ") Then
CMD.CommandType = CommandType.Text
Else
CMD.CommandType = CommandType.StoredProcedure
End If
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'fill the dataset
adapter.Fill(ds)
connection.Close()
Catch ex As Exception
' The connection failed. Display an error message.
Throw New Exception("Database Error: " & ex.Message)
End Try
Return ds
End Function
Once you have that, your SQL Execution + reading code is very simple:
'----------------------------------------------------------------------'
Dim CMD As New SqlCommand("GetProductName")
CMD.Parameters.Add("#productID", SqlDbType.Int).Value = ProductID
Dim DR As DataRow = ExecuteCMD(CMD).Tables(0).Rows(0)
MsgBox("Product Name: " & cstr(DR(0)))
'----------------------------------------------------------------------'
From MSDN
To execute a stored procedure returning rows programmatically using a command object
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
someVar = reader(0)
someVar2 = reader(1)
someVar3 = reader("NamedField")
End If
sqlConnection1.Close()
Simplest way? It works. :)
Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
Try
Using connection As New SqlConnection(ConnStrg)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim DTResults As New DataTable
DTResults.Load(reader)
MsgBox(DTResults.Rows(0)(0).ToString)
End Using
Catch ex As Exception
MessageBox.Show("Error while executing .. " & ex.Message, "")
Finally
End Try
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
Dim adapter As System.Data.SqlClient.SqlDataAdapter
Dim dsdetailwk As New DataSet
Try
adapter = New System.Data.SqlClient.SqlDataAdapter
adapter.SelectCommand = cmd
adapter.Fill(dsdetailwk, "delivery")
Catch Err As System.Exception
End Try
sqlConnection1.Close()
datagridview1.DataSource = dsdetailwk.Tables(0)
My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code
Please make sure that your procedure return some rows
Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
Try
Connection.Connect()
debug.print("Look up account number " & AccountNumber)
Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
Dim DST As New DataSet
DP.Fill(DST)
Return DST.Tables(0)
Catch ex As Exception
Return Nothing
End Try
End Function

How to use ACE OLEDB to import Excel data into VB?

Originally I was using Office Interop to import data, but that was a headache and a half for both me and my computer. Right now I'm attempting to load it with ACE, but my data grid isn't being populated. Once that's up and running I need to know how to use that data in other ways, and how to grab specific cells of data from that DataSet. I'm using Visual Studio 2008, by the way.
Right now I have...
Public Function funcUpdate(ByVal sFileLoc As String) As Boolean
'Determine connection string properties
Dim dbProperty As String
If updFileExt = ".xlsx" Then
dbProperty = "Excel 12.0 Xml;HDR=No"
ElseIf updFileExt = ".xls" Then
dbProperty = "Excel 12.0;HDR=No"
Else
MessageBox.Show("FATAL: File type error on updater", "OHGAWDNO", MessageBoxButtons.OK, MessageBoxIcon.Error)
updateTerm()
Return False
End If
Dim dbConn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & updFile & ";Extended Properties=" & dbProperty & ";")
Dim dbCommand As New OleDb.OleDbDataAdapter("select * from [sheet1$]", dbConn)
Dim dtSet As New DataSet
Try
dbCommand.TableMappings.Add("Table", "ExcelTest")
dbCommand.Fill(dtSet)
Form1.DataGrid1.DataSource = dtSet.Tables(0)
Catch exlErr As Exception
Finally
dbConn.Close()
End Try
updateTerm()
End Function
Try to do this.
Dim path As String = "c:\example.xlsx"
Dim constr As String = [String].Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;" & _
"HDR=YES;IMEX=1;""", path)
Dim adapter As New OleDbDataAdapter
Using cn As New System.Data.OleDb.OleDbConnection(constr)
Try
cmdselcet = New OleDbCommand("SELECT * FROM [Sheet1$]", cn)
cn.Open()
adapter.SelectCommand = cmdselcet
Dim ds As DataSet
ds = New DataSet
'Display
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
MsgBox("Done!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using