operator/operand type mismatch when update dbf file - vb.net

i have a program needs to update data in dbf file. but it keeps appear error 'operator/operand type mismatch'. here is sample code :
Dim con As OleDbConnection = New OleDbConnection("Provider=vfpoledb;Data Source=C:\folder\paytran.dbf;Collating Sequence=machine;")
Try
Dim strSQL As String = "UPDATE paytran.dbf SET workhr = 20 WHERE empno = 102"
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
' Using DataAdapter object fill data from database into DataSet object
myDA.Fill(myDataSet, "MyTable")
' Binding DataSet to DataGridView
DGV.DataSource = myDataSet.Tables("MyTable").DefaultView
con.Close()
con = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Select Data")
Finally
If con IsNot Nothing Then
con.Close()
End If
End Try
please help me..

Its your connection string. The connection string should only have to point to the PATH where the data files are located, then all the SQL based commands will by default be able to see any .DBF tables IN that path (or forward if subpaths exists).
Data Source=C:\folder
instead of
Data Source=C:\folder\paytran.dbf
So, now if you have 30 tables in the "C:\folder", you can now query from ALL of them as needed.

You need to explicitly open and close the DBF. Try:
Dim strSQL As String = "Use paytran in 0 shared;UPDATE paytran SET workhr = 20 WHERE empno = 102;use in select('paytran')"

Related

I get only column headers using sqldatareader and datagridview

I have a SQL Server 2008 express with a database and a table and using VB 2010 express.
I am trying to read from that table with sqldatareader, but I only one row in the datagridview with the column headers, no row with data.
What am I doing wrong? (I'm a newbe).
The connection string is :
Data Source=xxxxxxxxxx\SQLEXPRESS;Initial Catalog=Masteca_Inventory;Integrated Security=True
Dim searchStr As String = ""
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sqlStr As String
Public bindingSource1 As New BindingSource()
connetionString = My.Settings.SQLconnSTR
sqlStr = "SELECT * FROM Piese WHERE " & searchStr 'searchStr is OK I fill it elsewhere
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sqlStr, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
Using sqlReader
Dim dTable As New DataTable
dTable.Load(sqlReader)
bindingSource1.DataSource = dTable
End Using
SearchReport.DataGridView1.DataSource = bindingSource1
'SearchReport is another form
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
SearchReport.Show()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
You are not reading the data as a group (you are fetching only one result).
You will need to adjust the code to use a While sqlReader.Read;
Example;
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
Try
'Do the work needed
rowResult += sqlReader(0) 'This will contain the result script
Catch ex As Exception
'Catch exception
End Try
End While
Something like that should work (I have not tested the code but the concept is the same).
PS - I strongly suggest you adjust your script to add a Where clause and / or the columns needed (Select * is not a "good practice")
Hope this helps.

VB | Loading SQL Query into Combobox

I am trying to fill a combobox with a SQL Result
I think my problem is handling the data in the datatable form.
Dim sql As String
Dim sqlquery As String
Dim ConnectionString As String
ConnectionString = "Data Source=(local);Initial Catalog=Control;Persist Security Info=True;User ID=user;Password=pass"
sqlquery = "Select dbName from Databases"
Using connection As SqlConnection = New SqlConnection(ConnectionString)
connection.Open()
Using conn As SqlCommand = New SqlCommand(sqlquery, conn)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(cmboxDatabaseName)
End Using 'comm
End Using 'conn
When I run the program I just stare at a sad empty combobox.
Almost right, but you need to Load the datatable using the DataReader.
Then assing the DataTable to the DataSource of the Combo
Using connection As SqlConnection = New SqlConnection(ConnectionString)
connection.Open()
Using comm As SqlCommand = New SqlCommand(sqlquery, connection)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rs)
' as an example set the ValueMember and DisplayMember'
' to two columns of the returned table'
cmboxDatabaseName.ValueMember = "IDCustomer"
cmboxDatabaseName.DisplayMember = "Name"
cmboxDatabaseName.DataSource = dt
End Using 'comm
End Using 'conn
Also you could set the combobox ValueMember property to the name of the column that you will use as key for future processing and the DisplayMember property to the column name that you want to display as text to choose from for your user
you can also do it as
Dim Con = New SqlConnection(_ConnectionString)
Dim cmdAs New SqlCommand
Dim dr As New SqlDataReader
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.

Loop through action

I am new to visual basic, however I need to loop through rows in a data table and use the values to in a test script, the script is as follows -
Public Function TestMain(ByVal args() As Object) As Object
StartApp(URL)
' HTML Browser '
Browser_HtmlBrowser(Document_HomePage(),DEFAULT_FLAGS).Maximize()
Button_AddNewProfilesubmit().Click()
'here is where the rows would be read and the loop would start'
Text_Ctl00MainContentProfileNa().Click(AtPoint(6, 13))
Browser_HtmlBrowser(Document_Http1921685526UserCon(), DEFAULT_FLAGS).InputChars("dataBase_Row_Value")
Table_HtmlTable_1().Click(AtCell( _
AtRow(AtIndex(0)), _
AtColumn(AtIndex(1))))
'here is where the loop would end after all rows had been read'
Return Nothing
End Function
I have an idea to achieve this, first doing a database connection, then create the loop -
Dim pName As String
Dim datas As DataSet
Dim datar As DataRow
Dim oledat As SqlDataAdapter
oledat = New SqlDataAdapter("SELECT COLUMN FROM DATABASE",ConnectionString)
oledat.Fill(datas)
For Each datar In datas.Tables(0).Rows
pName = datar.Item("PROFILENAME")
Text_Ctl00MainContentProfileNa().Click(AtPoint(6, 13))
Browser_HtmlBrowser(Document_Http1921685526UserCon(), DEFAULT_FLAGS).InputChars(pName)
Table_HtmlTable_1().Click(AtCell( _
AtRow(AtIndex(0)), _
AtColumn(AtIndex(1))))
Next
However this is breaking, even though there are no errors in Visual Studio, there is only the warning that datas is used before it is assigned the values. Where am I going wrong?
I believe you must initialize a new dataset before working with it. Example:
Dim ds As DataSet = New DataSet()
Dim connection As OleDb.OleDbConnection
Dim command As OleDb.OleDbCommand
Dim adapter As New OleDb.OleDbDataAdapter
Dim connString As String = "my Connection string stuff;"
connection = New OleDb.OleDbConnection(connString)
Try
'open the connection
If connection.State = ConnectionState.Open Then
Else
connection.Open()
End If
'fill each data table
command = New OleDb.OleDbCommand(selectOne, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "someTableName")
Catch ex As OleDb.OleDbException
'error, do something
Finally
'close everything down
adapter.Dispose()
If (Not command Is Nothing) Then
command.Dispose()
End If
connection.Close()
End Try
This example uses OLEDB but should be comparable to what you are doing. Once you fill it, you should be able to iterate over the tables. But, first, check to make sure you have a dataset created first:
If (ds IsNot Nothing) Then
'do for statement here
End If
If this does not work, let me know.

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

duplicate in updating ms access database

Here is the error:
http://screencast.com/t/ZDVhNmJiOTgt
Please help, here is my code:
what can I do to solve this error
Try
If MessageBox.Show("Save and update database?", _
"Confirmation", MessageBoxButtons.YesNo) = _
Windows.Forms.DialogResult.Yes Then
Dim idXs As Integer
Dim dSet As New DataSet
Dim conn As New OleDb.OleDbConnection
Dim strSQL As String
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS DATABASE\search.mdb"
conn.Open()
strSQL = "Select * From GH"
Dim da As OleDbDataAdapter
da = New OleDb.OleDbDataAdapter(strSQL, conn)
da.Fill(dSet, "GH") 'fill dataset
'code for editing records
Dim cb As New OleDbCommandBuilder(da)
idXs = Form1.idX 'retrieve index from Form1
dSet.Tables("GH").Rows(idXs).Item(0) = TextBox1.Text
dSet.Tables("GH").Rows(idXs).Item(1) = TextBox2.Text
dSet.Tables("GH").Rows(idXs).Item(2) = TextBox3.Text
dSet.Tables("GH").Rows(idXs).Item(3) = TextBox4.Text
da.Update(dSet, "GH") 'update database
conn.Close() 'close connection
reloadMyMain() 'show new changes in form1 if any
Else
DSET.RejectChanges() 'cancel delete
End If
Catch ex As Exception
MsgBox(ex.ToString) 'show exception message
End Try
you need to check the table in the DB - one of the columns is either indexed and can only contain unique values, or has some other limitation.
you enter a data into that column that it can not hold.
Try to "UPDATE" the Data Manually directly on the table and you will see what is wrong...
It seems you just don't have the file F:\ACCESS DATABASE\search.mdb.
Check the path to your access database file.
The error message that you point to reads:
'F:\ACCESS DATABASE\search.mdb' is not a valid path.
Apparently you mistyped the path to the db in the conn.ConnectString = ... line.