Why is Access Database Engine giving a weird error? - vb.net

The following code crashes with this error:
System.Data.OleDb.OleDbException: 'Too few parameters. Expected 1'
Dim selectString As String = "SELECT * FROM Products WHERE id = ?;"
Dim cmd As OleDbCommand = New OleDbCommand(selectString, dbOleDB)
cmd.Parameters.AddWithValue("ID", id)
Dim reader As OleDbDataReader = cmd.ExecuteReader()
If I do a repair on the Access Database Engine installation the error disappear for a day.
The same thing happens on multiple machines running different versions of Windows.
This problem started about 2 weeks ago.
Anyone have any idea whats happening?

OleDbCommand does not behave right with named parameters.
Try this instead,
Dim selectString As String = "SELECT * FROM Products WHERE id = ?;"
Dim cmd As OleDbCommand = New OleDbCommand(selectString, dbOleDB)
cmd.Parameters.Add("#ID", OleDbType.BigInt).Value = id; '#ID essentially means nothing here. The Adds you make have to be sequential
Dim reader As OleDbDataReader = cmd.ExecuteReader()

Related

Error trying to load ODBC connection to dataset

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)

How to populate a combobox from two different SQL Server database tables

I am trying to create a system that will load items from a database. There are two comboboxes; combobox1 which loads items from database table 1 and combox2 which loads items from database table 2.
Both tables are in the same database.
Here is was I tried but when I run the system I get this error:
(Conversion from string "SELECT * FROM dbo.Dishes" to type 'Long' is not valid.)
Here is the code I'm using:
Dim connection As New SqlConnection("Server = DESKTOP-1373H91; Initial Catalog = MealPreOrderSystem; Integrated Security = True")
connection.Open()
Dim query As String = "SELECT * FROM dbo.Dishes" And "SELECT * FROM dbo.Desserts"
Dim cmd As SqlCommand
cmd = New SqlCommand(query, connection)
Dim reader As SqlDataReader
reader = cmd.ExecuteReader
While reader.Read
cbxType.Items.Add(reader.Item("MealName"))
cbxType.Items.Add(reader.Item("DessertName"))
End While
connection.Close()
In VB.NET,AND is an operator.It is used to perform conjunction between either Booleans or Integers/Doubles/any numeric expression.Lets take your query string as an example :
Dim query As String = "SELECT * FROM dbo.Dishes" And "SELECT * FROM dbo.Desserts"
You are using AND here to join 2 sentences/strings which wouldn't result in anything rather it is trying to cast it as a Long.
Try to execute this command in SQL and you won't find any luck :(.
Your statements are correct :
SELECT * FROM dbo.Dishes
SELECT * FROM dbo.Desserts
But the way you are trying to achieve your goals is incorrect :(.
To get the data from the database into your combobox, what you can do is either use two comboboxes with separated SQL Queries/SQL Commands or you can use one combobox where you add data from both the databases but separate them with some special characters such as a comma ,
A sample may look like :
With one combobox
Dim cmd1 as new SqlCommand("SELECT * FROM dbo.Dishes",connection)
Dim dr as SqlDatareader = cmd1.ExecuteReader
While dr.Read
mycombo1.Items.Add(dr(0)) ' Here 0 is the column count,change it as required
End while
Dim cmd2 as new SqlCommand("SELECT * FROM dbo.Desserts",connection)
Dim dr2 as SqlDatareader = cmd2.ExecuteReader
While dr2.Read
mycombo2.Items.Add(dr2(0)) ' Here 0 is the column count,change it as required
End while
With 1 combobox
Here it gets a bit complicated.Firstly you need to populate your combobox from the data received from the first dataReader.Then, when the 2nd datareader is reading the data , you need to update the existing data/Item of the combobox keeping the existing data/item but adding new data/item to each existing data/item(separating them with ,).
Sample :
Dim i as Integer
Dim cmd1 as new SqlCommand("SELECT * FROM dbo.Dishes",connection)
Dim dr as SqlDatareader = cmd1.ExecuteReader
While dr.Read
mycombo1.Items.Add(dr(0))
End while
Dim cmd2 as new SqlCommand("SELECT * FROM dbo.Desserts",connection)
Dim dr2 as SqlDatareader = cmd2.ExecuteReader
While dr2.Read
mycombo1.Items(i) = myconbo1.Items(i) & "," & dr2(0)
i = i + 1
End while
Now, NOTE THAT I AM USING MULTIPLE DATAREADERS WITH THE SAME CONNECTION ,SO YOU MAY NEED TO INCLUDE MultipleActiveResultSets=True IN YOUR CONNECTION STRING or ENCLOSE THE DATAREADERS IN USING STATEMENTS or CALL dataReader.Close AFTER EACH DATAREADER HAS COMPLETED READING FROM THE DATABASE
This will solve your issue :)
Looks like you don't know how to write SQL queries (and your VB syntax itself looks faulty - string AND string?).
Dim connection As New SqlConnection("Server = DESKTOP-1373H91; Initial Catalog = MealPreOrderSystem; Integrated Security = True")
Dim query As String = <cmdString>
SELECT MealName as Name FROM dbo.Dishes
union
SELECT DessertName as Name FROM dbo.Desserts
</cmdString>
Dim cmd As SqlCommand
Dim reader As SqlDataReader
connection.Open()
cmd = New SqlCommand(query, connection)
reader = cmd.ExecuteReader
While reader.Read
cbxType.Items.Add(reader.Item("Name"))
End While
connection.Close()
Note: You are saying 2 comboboxes but your code seemed to be loading all the items to a single combobox. If you really need 2 comboboxes then use 2 SqlCommand and Reader loops (actually it would be better if you simply have used Linq for this).
You should be a bit more specific on what columns you are pulling from the 2 tables. if they are similar, you could write a sql query to UNION ALL the fields with a simple control to identify which record came from which table.
Example of SQL command string:
"SELECT 'M' AS Ctl, MealName AS aName FROM dbo.Dishes " &
"UNION ALL " &
"SELECT 'D' AS Ctl, DessertName AS aName FROM dbo.Desserts"
As mentioned by many here already, it seems like you are referencing only 1 ControlBox to list the fields returned cbxType
below is the reader (adapted to 2 ComboBoxes):
While reader.Read
Select Case reader.Item("Ctl")
Case "M"
cbxMType.Items.Add(reader.Item("aName"))
Case "D"
cbxDType.Items.Add(reader.Item("aName"))
End Select
End While
Hope this helps

Execute two sql commands related in VB.NET

I'm trying to execute two related sql commands in a single function top update my column xamlfile by a new xamlfile --> u
Here's my code
Public Shared Function updatetest()
Dim c As SqlConnection = openConnection("Data Source=GENIOP40;Initial Catalog=TF5100_new;Integrated Security=true")
Dim c2 As SqlConnection = openConnection("Data Source=GENIOP40;Initial Catalog=TF5100_new;Integrated Security=true")
Dim cmd As New SqlCommand("SELECT xamlfile, id_wkfw_task from WKFW_Tasks Where xamlfile like '%ExecuteTask%' order by name", c)
Dim rd As SqlDataReader = executereader(cmd)
Dim listxaml As New List(Of String)
While rd.Read
Dim u As String = GetString(rd, "xamlfile")
Dim Id As Guid = GetGuid(rd, "id_wkfw_task")
u = Regex.Replace(u, "(?<=<t[1-2]|:ExecuteTask[^><]+)\bTache", "TaskID")
u = u.Replace("'", "''")
Dim cmd2 As New SqlCommand("UPDATE WKFW_Tasks set xamlfile=#xmlfile where id_wkfw_task=#id_t", c2)
cmd2.Parameters.Add("xmlfile", SqlDbType.NVarChar).Value = u
cmd2.Parameters.Add("id_t", SqlDbType.UniqueIdentifier).Value = Id
cmd2.CommandTimeout = 0
executeNonQuery(cmd2)
c2.Close()
End While
rd.Close()
c.Close()
End Function
My problem is : when I close the reader after the loop, my first command is no more executed, and I need it to be executed so my second command can work, and if I don't close my reader I have an error, any suggestions please ?
Change your initial connectionstring to
Dim c As SqlConnection = openConnection("Data Source=GENIOP40;
Initial Catalog=TF5100_new;Integrated Security=true;
MultipleActiveResultSets=true")
See MSDN on MultipleActiveResultSets
Now you don't need anymore to have the DataReader closed between the calls and you can execute the command using the only one connection. However I recommend to move the creation of the update command and its parameters outside the loop.
Inside the loop just update the parameter values and execute
Dim cmd2 As New SqlCommand("UPDATE WKFW_Tasks set xamlfile=#xmlfile where id_wkfw_task=#id_t", c)
cmd2.Parameters.Add("xmlfile", SqlDbType.NVarChar)
cmd2.Parameters.Add("id_t", SqlDbType.UniqueIdentifier)
While rd.Read
....
cmd2.Parameters("xmlfile")..Value = u
cmd2.Parameters("id_t").Value = Id
executenonquery(cmd2)
End While

Several rows in SQL Developer but VB says no rows

Dim Test123 As String
Dim Conn As OleDb.OleDbConnection = New OleDbConnection("Private")
Conn.Open()
Dim mySelectQuery As String = "SELECT mti_part_no,sum(mpcs.shop_inv_history.quantity) As FebQTY from mpcs.shop_inventory, mpcs.shop_inv_history where mpcs.shop_inv_history.date_time Like '%Feb% %2015%' AND comments = 'CHECK ITEM OUT' AND mpcs.shop_inventory.si_key=mpcs.shop_inv_history.si_key AND SHOP_INVENTORY.CATEGORY BETWEEN 900 and 999 AND SHOP_INVENTORY.SCRAP_FLAG <> 1 group by mti_part_no order by FebQTY DESC"
Dim CMD As OleDbCommand = New OleDbCommand(mySelectQuery, Conn)
Dim Myreader As OleDbDataReader
Myreader = CMD.ExecuteReader()
Myreader.Read()
Test123 = Myreader("FebQTY")
There are 180 rows when I copy/paste my query into SQL Developer, however whenever I try to use this in VB.NET to populate my listview, I was getting nothing. So I tossed it into the above code just to see what I was quickly getting back from FebQTY and the error is that there are no rows, same with mti_part_no. Can't figure out what the problem is.

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