Error trying to load ODBC connection to dataset - vb.net

I am trying to connect to an ODBC connection.
This works.
Dim cn As OdbcConnection
cn = New OdbcConnection("DRIVER={SQL Server};SERVER=ServerName;UID=UserName;" &
"PWD=Password;DATABASE=dbName;")
Dim mystring As String = "SELECT * FROM dbo_lData WHERE S_DT > #3/18/2018#"
Dim cmd As OdbcCommand = New OdbcCommand(mystring)
cn.Open()
MsgBox("Connected")
cn.Close()
I've tried a couple of variations using different code that I've found on the internet, but I keep getting the same error. Error 42000, incorrect syntax near #. Here is the code.
Dim selectSQL As String = "SELECT * FROM dbo_lData WHERE S_DT > #3/18/2018#"
cn = New OdbcConnection("DRIVER={SQL Server};SERVER=ServerName;UID=UserName;" &
"PWD=Password;DATABASE=dbName;")
Dim custDA As New OdbcDataAdapter
Dim selectCMD As OdbcCommand = New OdbcCommand(selectSQL, cn)
custDA.SelectCommand = selectCMD
Dim custDS As DataSet = New DataSet
custDA.Fill(custDS, "lData")
DataGridView1.Visible = True
DataGridView1.DataSource = custDA
I'm pretty lost on this, but what I am trying to do is just...
Make ODBC Connection
Load results, preferable into a datatable
Set datagridview.datasource = datatable

The error you are getting is referring to your Select statement. As the comments said use parameters. First double check the data type of S_DT column. I wonder why you are using ODBC when the SQL server native provider SQLClient will yield better results.
Dim cn As New OdbcConnection("connection string")
Dim cmd As New OdbcCommand("SELECT * FROM dbo_lData WHERE S_DT > #sdate", cn)
cmd.Parameters.Add("#sdate", OdbcType.Date)

Related

How to use cmd.parameters.add("#ID") SQL, VB.NET

Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM"
Using command As New SqlCommand(sql, conn)
Using adapter As New SqlDataAdapter(command)
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
'command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text)
adapter.Fill(dt)
TextBox1.Text = dt(0)(0)
End Using
End Using
End Using
This code working properly asper my expectation. When I use "where ID=#ID" in sqlcommand It's showing error: 'Input string was not in a correct format.'
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
Using adapter As New SqlDataAdapter(command)
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text)
adapter.Fill(dt)
TextBox1.Text = dt(0)(0)
End Using
End Using
End Using
In this code I'm getting error. Could someone help me how to declare "#ID". Thank you..
Please check the error description.
enter image description here
That's maybe because you are trying to add parameters using the statement of the adapter.
Try this:
Dim idValue As Int = Convert.ToInt32(TextBox1.Text)
Dim dt As DataTable = New DataTable()
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
command.Parameters.Add("#ID", SqlDbType.Int).Value = idValue
Using adapter As New SqlDataAdapter(command)
adapter.Fill(dt)
End Using
End Using
End Using
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
TextBox1.Text = dt(0)(0)
If you want to change the way you using to parse string to int:
Dim idValue As Int = Integer.Parse(TextBox1.Text)
Dim dt As DataTable = New DataTable()
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
command.Parameters.AddWithValue("ID", idValue)
Using adapter As New SqlDataAdapter(command)
adapter.Fill(dt)
End Using
End Using
End Using
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
TextBox1.Text = dt(0)(0)
it looks like in your broken code you need/want to have multiple "id" or more than one value. You can do this, but you ALSO then have to add the parameters to the source sql string.
You can't just add, or have multiple #ID values for the one "#ID".
If you want more than one ID value in the same sql query, then you have to add multiple "#id1" then "#id2" and so on to the sql text for this to work.
So, if you have ONE "#ID" then fine.
However, if you have say id 2, 134, 222?
Then you would have to add each parmater to the sql string.
You can do it this way:
dim strSQL as string = "SELECT * FROM MyTable"
dim strWhere as string = ""
dim cmdSQL as New Sqlcommand("", new Sqlconneciton("con string here")
' add first #id
strWhere = "#ID1"
cmd.SQL.Paramters.Add("#ID1", SqlDbType.Int).Value = 124
' add 2nd #!id
strWhere &= ",#ID2"
cmd.SQL.Paramaters.Add("#ID2", SqlDbType.Int).Value = 456
' and so on and so on
cmdSQL.CommandText = strSQL & " WHERE ID IN (" & strWhere & ")"
dim rstData as new DataTable()
cmdSQL.conneciton.Open()
rstData.Load(cmdSQL.ExectuteReader())
Note VERY interesting that you can create the sql command object, and are 100% free to add as many new parameters as possible to the cmdSQL object, and EVEN do so without having the sql command/text set for the sql command object.
However, you EVENTUALLY will have to setup/provide/have the sql shoved into that command object. So, build up the multiple "#id1, #id2" etc., and then shove that whole correct sql string into the cmdSQL object, and it will work.
However, as noted, you are 100% free to add as many parameters to the cmdSQL object, and even do so without having the SQL made/set/created for the cmdSQL object. They thus can be created 100% independent of the existing sql string/text (or better said lack of that sql string during the parameter adding process).

Syntax error in from clause - no reserved words DA.fill

Having some issues with the myDataAdapter.fill line, getting the error "syntax error in From clause" looked around at other solutions and none have worked, most seem to be about reserved words - all out of ideas, help!
'retrieve the connection string from the ConnectionString Key in Web.Config
'string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Woof.mdb"
Dim myDataSet As New System.Data.DataSet("Email")
'create a new OleDB connection
Dim conn As New System.Data.OleDb.OleDbConnection(connectionString)
'pass the Select statement and connection information to the initializxation constructor for the OleDBDataAdapter
Dim myDataAdapter As New System.Data.OleDb.OleDbDataAdapter("SELECT Email FROM Email-list", conn)
'Fill the dataset and table with the data retrieved by the select command
myDataAdapter.Fill(myDataSet, "Email")
Dim str As String = myDataSet.ToString
Label3.Text = str
Use the query
Dim myDataAdapter As New System.Data.OleDb.OleDbDataAdapter("SELECT Email FROM [Email-list]", conn)

Update Access database records by column, row known

This is what I've got so far :
Dim myCONN As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\Baza.mdb")
Dim cmd1 = New OleDbCommand("SELECT ID FROM Baza WHERE NAZIV=#XXNAZIV")
cmd1.Parameters.AddWithValue("#XXNAZIV", TextBox2.Text)
cmd1.Connection = myCONN
myCONN.Open()
Dim result = cmd1.ExecuteReader()
While (result.Read())
Dim rowx As Integer = GetTextOrEmpty(result("ID"))
End While
I've found the row (rowx) in which I would like to change values in 20 corresponding columns (namesID : NAZIV, SIFRA,...). Data is already presented in textboxes (textbox1...), but I don't know how to finish this code with UPDATE and how to insert changed values back to Access.
Dim cmdText As String = "UPDATE Baza SET NAZIV=#XXNAZIV Where ID=SomeId"
Using con = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = h:\Baza.mdb")
Using cmd = new OleDbCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#XXNAZIV",TextBox2.Text)
cmd.ExecuteNonQuery()
End Using
End Using
This should help you to solve your problem, of course you will have to pass ID parameter to query also.
Reference

operator/operand type mismatch when update dbf file

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')"

Saving record with dataset

I want to save a record in the database using a dataset, but my data is not committing into my database.
My code can be viewed below:
Dim mydataset1 As New MyDataSet
Dim row As DataRow = mydataset1.Tables("testtable").NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
mydataset1.Tables("testtable").Rows.Add(row)
Any help will be appreciated
A DataSet/DataTable is a offline/in-memory representation of your database. If you want to update the database, you need to use a DataAdapter.
For example (assuming you're using MS-Sql-Server):
Public Function UpdateDataSet(dataSet As DataSet) As Int32
Using con = New SqlConnection(My.Settings.SqlConnection)
Dim sql = "INSERT INTO TUser(Name,Address)VALUES(#Name,#Address)"
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
cmd.Parameters.Add(New SqlParameter("#Address", SqlDbType.VarChar))
Using da = New SqlDataAdapter()
da.InsertCommand = cmd
con.Open()
Dim rowCount = da.Update(dataSet)
Return rowCount
End Using
End Using
End Using
End Function
I could be rusty here since its a long time since I wrote any VB.NET or used data adapters/datasets/datatables but I think if you decide to take that route you would need code like this:
Dim connection As New SqlConnection("#####YourConnectionString#####")
connection.Open()
Dim adapter As New SqlDataAdapter("SELECT * FROM testtable", connection)
' For the line below to work, you must have a primary key field in "testtable"
Dim builder As New SqlCommandBuilder(adapter)
Dim testtable As New DataTable("testtable")
adapter.Fill(testtable)
Dim row As DataRow = testtable.NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
testtable.Rows.Add(row)
adapter.Update(testtable)
connection.Close()