How to make connection VFP database with VB.NET - vb.net

I'm creating a system that use foxpro as a database. I keep getting this error error [42S02][microsoft][ODBC visual foxpro driver] not a table when I want to connect VFP database with Visual Studio. When I add data connection in the visual studio, it shows connection success, but when I try to open the table, it shows the error.
This is a VB.Net system that use database foxpro 9. I have use mysql as the database and it work, but when I try to use foxpro database I get an error.
Imports System.Data.Odbc
Imports System.Data.OleDb
Public Class login
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim oConn = CreateObject("adodb.connection")
oConn.ConnectionString = "Provider=vfpoledb;DSN=visual_foxpro"
oConn.Open()
Dim conn = New OleDbConnection()
Dim cmdString As String = "SELECT * FROM `login` WHERE `staffID`= #staffid AND `staffName`= #staffname"
Dim cmd As New OleDbCommand(cmdString, oConn)
cmd.Parameters.Add(New OleDbParameter("staffID", CType(txtStaffID.Text, String)))
cmd.Parameters.Add(New OleDbParameter("staffName", CType(txtStaffID.Text, String)))
Dim adapter As New OleDbDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("Staff ID or Staff Name not available")
Else
MessageBox.Show("Welcome " & txtStaffName.Text)
Dim form As New formLeave
form.PassStaffid = txtStaffID.Text
form.PassStaffName = txtStaffName.Text
form.Show()
Me.Hide()
End If
End Sub
End Class
I expected the system can login using the database.

VFP database versions later than 6.x do not have an official ODBC driver from Microsoft. If you HAVE TO use ODBC, then you can find alternative drivers from sources like Sybase ADS. I use OLEDB instead successfully well.
While your code might work with MySQL, that is not the way you should write it. Also, it is MySQL specific, it wouldn't work in say MS SQL Server or postgreSQL either. You should read the documentation on the backend you are using. In VFP (or MS SQL Server, postgreSQL ...), you don't use back tics as table and field name identifiers. In VFP, if need be, to use name identifiers you could use single, double quotes or square brackets but you would need to enclose with parentheses (and use only for table name in an SQL query). Anyway, the easy way is to simply not to use identifiers at all.
Also, with an ODBC or OLEDB query, you need to use ? as parameter placeholders. Using #staffID wouldn't normally work in MySQL, ... either, but driver makers decided to support them for those backends.
From your messageBox messages, looks like you expect to get a single row for that query (I don't know why you use both staffId and staffName if staffId is primary key). Anyway here is your query in VB.Net:
Imports System.Data.OleDb
Public Class login
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim strConn As String = "Provider=VFPOLEDB;Data source=c:\MyDataFolder\"
Dim strQuery As String = <sql>SELECT *
FROM login
WHERE staffID=? AND staffName=?
</sql>
Using cn As New OleDbConnection(strConn)
Using cmd As New OleDbCommand(strQuery, cn)
cmd.Parameters.Add("#staffid", OleDbType.VarChar).Value = txtStaffID.Text;
cmd.Parameters.Add("#staffname", OleDbType.VarChar).Value = txtStaffName.Text;
cn.Open()
Dim rdr As OleDbDataReader = cmd.ExecuteReader()
If rdr.Read()
MessageBox.Show("Welcome " & txtStaffName.Text)
Dim form As New formLeave
form.PassStaffid = txtStaffID.Text
form.PassStaffName = txtStaffName.Text
form.Show()
Me.Hide()
Else
MessageBox.Show("Staff ID or Staff Name not available")
End If
cn.Close()
End Using
End Using
End Sub
End Class

Related

'Fill: SelectCommand.Connection property has not been initialized.'

I am using a visual studio 2022 vb.net and mssql management studio.
login form
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles Btnlogin.Click
cn.Open()
cm = New SqlClient.SqlCommand("select * from table_user where username like '" & username.Text & "' and password like '" & password.Text & "'and usertype= '" & usertype.SelectedItem & "'", cn)
dr = cm.ExecuteReader
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("You are login as " + dt.Rows(0)(2))
If (usertype.SelectedIndex = 0) Then
Dim a As New dashboard
a.Show()
Me.Hide()
Else
Dim b As New Admin
b.Show()
Me.Hide()
End If
Else
MessageBox.Show("Username or Password Incorrect. CONTACT ADMINISTRATOR!")
End If
cn.Close()
End Sub
Module
Imports System.Data.SqlClient
Module Module1
Public cn As New SqlConnection("Data Source=DESKTOP-7POF5HE\SQLEXPRESS;Initial Catalog=dict;Integrated Security=True")
Public cm As New SqlCommand
Public dr As SqlDataReader
Public sda As SqlDataAdapter = New SqlDataAdapter(cm)
Public dt As DataTable = New DataTable()
End Module
CAN YOU HELP ME TO SOLVE THIS?
Seems there are several issues with this code.
In your module, you create the command object and the data adapter object. But in the form method, you create a new command object. But that will not update the data adapter to use that new command object. Class variables are reference types. They just point to an object in the memory somewhere. Your cm variable will point to the new command object, but your sda object will internally still point to the old command object.
Furthermore:
You are using both a data reader and a data adapter. Both have their pros and cons, but you probably don't need (or want) to use them both at the same time. I assume you want to use the data adapter. So you can drop the dr = cm.ExecuteReader line in the form method.
Since you will probably always want to create command objects and data adapter objects on the fly (as I would), you could remove them from the module. Just create them both as local variables in your form method.
Try to use the Using statement for such objects. They need to be disposed of nicely when the form method finishes. Otherwise they might keep valuable system resources in use until the .NET garbage collector disposes them (which will probably occur when you close your application, not earlier).
Also be careful with concatenating SQL statements from variables. What would happen here if you enter this text in your username textbox?: ';delete from table_user;--
Hint: Do not actually try it! It will try to delete all your users from the database table table_user. Just try to manually reproduce the SQL string that will be built in your form method. This is called an SQL injection attack. To avoid such nasty things, it's easiest to use SQL parameters in your SQL statements and pass them separately to your command object.

How can I add the value of a single Cell from Access database to a string variable

As the title says I have a MS Access database from where I need to find a specific dataset determined by a String Value. the reason for having to do this is so I can find the value of a single cell in this datase which has to be used as a path to find a certain file. my approach so far is the following:
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ExaptLokal.accdb")
Dim cmd As New OleDb.OleDbCommand
Dim dt As New DataTable
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT NC_KEY FROM EXAPT_NC_KOPF_DATEN WHERE NC_PROGRAMM_NAME =" & ProgrammNr.Text.ToString
MsgBox(sql)
conn.Open()
cmd.Connection = conn
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
fullpath = dt.ToString
at the end I would like to have the result from my SQL Query as the value of my "fullpath" variable but so far the da.Fill(dt) row is giving me a hard time saying there is a conflict with the datatype.
Is the datatable even needed in this case or might I be able to skip that step and get the result of the query directly in the fullpath variable?
Thanks to everyone in advance
Edit: Thanks for the help (though not the friendliest but who am I to judge) I finally got it to work with the Execute Scalar method. I would just wish newbies to this website would be greeted a little better lol
have a great day
I moved the connection string to a class level variable so you can use it in other methods.
I separated your data access code from your user interface code passing the value from the text box to a function that returns the path.
I changed your select statement to use parameters. Always use parameters to avoid sql injection and avoid errors.
Use Using...End Using blocks to ensure that your database objects are closed and disposed. This Using block covers both the command and the connection.
You can pass the .CommandText and the .Connection directly to the constructor of the command.
When adding parameters to the parameters collection you provide the parameter name, the datatype form the database, and the size of the field. I had to guess at the type and size so, check your database for the actual values.
Since you are expecting a single value you can use .ExecuteScalar.
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ExaptLokal.accdb"
Private Function GetPath(ProgrammNr As String) As String
Dim fullpath As String
Dim sql = "SELECT NC_KEY FROM EXAPT_NC_KOPF_DATEN WHERE NC_PROGRAMM_NAME = #ProgrmmNr"
Using conn As New OleDb.OleDbConnection(ConStr),
cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add("#ProgrmmmNr", OleDbType.VarChar, 100).Value = ProgrammNr
conn.Open()
fullpath = cmd.ExecuteScalar.ToString
End Using
Return fullpath
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fullpath = GetPath(ProgrammNr.Text)
End Sub

SQLite connection in sharpdevelop 4

I am struggling with some SQLite to VB.net code. I am using sharpdevelop 4.0 to try and connect to a SQLite database using SQLiteadmin. I have set up both and just need help in getting them to connect to each other when they mainform loads. I have put the code in mainform (see below) The database is called "KCB.db3". When i click the button i get an error message saying the connection is closed. What am i doing incorrectly?
Dim SQLconnect As New System.Data.SqlClient.SqlConnection
Dim SQLcommand As System.Data.SqlClient.SqlCommand
Dim SQLreader As System.Data.SqlClient.SqlDataReader
Sub Button1Click(sender As Object, e As EventArgs)
'Procedure to extract records from People table in Contacts SQLite database file
'Create an SQL command
SQLcommand = SQLconnect.CreateCommand
'Create SQL statement
SQLcommand.CommandText = "SELECT * FROM Staff"
'Extract data
SQLreader = SQLcommand.ExecuteReader()
While SQLreader.Read()
'Add record to listbox
msgbox(SQLreader("Staff_ID"))
msgbox(SQLreader("Staff_Surname"))
msgbox(SQLreader("Staff_First_Name"))
End While
'Clear SQL command buffer
SQLcommand.Dispose()
End Sub
Sub MainFormLoad(sender As Object, e As EventArgs)
SQLconnect.ConnectionString = "data source = KCD.db3"
SQLconnect.Open()
End Sub
I hope someone out there can help! Thanks
You seem to be trying to use the Microsoft Sql Server client to connect to SQLite which is not going to work.
If you install SQLite using NuGet you can then change your variables to be the following types:
Dim SQLconnect As New System.Data.SQLite.SQLiteConnection
Dim SQLcommand As System.Data.SQLite.SQLiteCommand
Dim SQLreader As System.Data.SQLite.SQLiteDataReader
Then the rest of your code should work.
The above SQLiteConnection, SQLiteCommand and SQLiteDataReader classes are in the System.Data.SQLite assembly which will be referenced after you install the SQLite NuGet package.

how to populate items from database in a listbox in vb.net

I was developing an application using oop concept.I have a class that has 2 attributes and have Get and Set methods namely WorkItemNumber and Description.
On the client side i have a list box used to populate the work items based on their description.Here's the code i wrote in the class o read items from the database.
Public Sub LoadWorkItem()
' Load the data.
' Select records.
Dim oWorkItem As WorkItem = New WorkItem()
Dim conn As New OleDbConnection
Dim data_reader As OleDbDataReader
conn = oWorkItem.GetDbConnection()
Dim cmd As New OleDbCommand("SELECT * FROM work_item ORDER BY [work item number]", conn)
data_reader = cmd.ExecuteReader()
'ListBox1.Items.Clear()
If data_reader.HasRows = True Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
Loop
End If
data_reader.Close()
data_reader = Nothing
cmd.Dispose()
cmd = Nothing
conn.Close()
conn.Dispose()
End Sub
How do i populate the listbox using the code,and if there's any improvement on the code please do tell me as well.Thank you
To poulate your ListBox, do this...
ListBox1.Item.Clear()
If data_reader.HasRows Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
ListBox1.Items.Add(New ListItem(Description, WorkItemNumber)
Loop
End If
As far as improvements, start by using a Using statement for the DB connection. In your code, if there is an exception while the database connection is open, it will never get closed. This is better...
Using conn As OleDbConnection = oWorkItem.GetDbConnection()
' Execute SQL and populate list...
End Using
The above code assures that your connection will be closed.
Then, turn on Option Strict and Option Explicit. This will force you to declare the Type for Description and WorkItemNumber and cast them as Strings when adding a ListItem. This will reduce run-time errors.
Finally, if this is anything but a small app you are doing as a learning experiment, you should read up on tiered application design. Your code is mixing UI, business logic, and data access in the same method. This is generally frowned upon.
Your "user interface" LoadWorkItem() method should ask a "core" method for a list of WorkItems.
Your core method should then ask a "data access" method for data.
The "data access" method should make the call to the database.
Happy coding.
Update: You can find excellent info about n-Tier architecture on MSDN. A good book to read once you grasp the fundamentals and have some confidence in .NET is Visual Basic .NET Business Objects.
Imports System.Data.SqlClient 'Reference The Sql Client
Public Class Form1
''Make sure to change the connection string below to your connection string this code only works for SQL DataBase. If Your connection String is wrong This will Not Work
Dim connString As String = "Data
Source=NameofYourSQLServer\SQLEXPRESS;Initial Catalog=NameOfYourDataBase;Integrated Security=True"
Dim tblDIV As DataTable
Dim daDIV As SqlDataAdapter
Dim dsDIV As New DataSet
Dim oCon As SqlConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oCon = New SqlConnection
oCon.ConnectionString = connString
dsDIV = New DataSet
' Select all Fields and order by ID or Replace * with name of Field
daDIV = New SqlDataAdapter("SELECT * FROM NameOfYourTable ORDER BY Id DESC", oCon)
'*** Define command builder to generate the necessary SQL
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(daDIV)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
Try
daDIV.FillSchema(dsDIV, SchemaType.Source, "DIV")
daDIV.Fill(dsDIV, "DIV")
tblDIV = dsDIV.Tables("DIV")
ListBox1.DataSource = tblDIV
ListBox1.DisplayMember = "NameOfTheFieldYouWanttoDisplay"
Catch ex As Exception
MsgBox("Encountered an Error;" & vbNewLine & ex.Message)
oCon.Close()
End Try
End Sub

Fill DataGridView with data from SQL

I want to fill a DataGridView with data returned from a SQL. So here is my code [I provided cause some people may think I'm asking for help before trying myself]
I want the DataGridView to be filled by a data from SQL not to show all the records.
The SQL "Select * From books where title='php%' Order By Title;"
useless code :( :'( :<
Imports System.Data
Imports System.Data.SqlClient
Public Class frmMain
Dim connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist" & " Security Info=True"
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.BooksTableAdapter.Fill(Me.TblBooks.books)
End Sub
Private Sub txtTerm_TextChanged() Handles txtTerm.TextChanged
If Trim(txtTerm.Text) = "" Then Exit Sub
Dim tblCustomBooks As New DataTable
Dim adpBooks As New OleDb.OleDbDataAdapter("Select * From books where title='php%' Order By Title", _
'"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist" & " Security Info=True")
adpBooks.Fill(tblCustomBooks)
BooksTableAdapter.Fill(tblCustomBooks)
'Dim myConnection As SqlConnection
'Dim myCommand As SqlDataAdapter
'myConnection = New SqlConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist" & " Security Info=True")
'myCommand = New SqlDataAdapter("Select * From books where title='php%' Order By Title", myConnection)
'Dim ds As DataSet = New DataSet()
'myCommand.Fill(ds)
'gridTable.DataSource = ds
End Sub
Looks like you've tried a number of different things, but it's not apparent from your code what order you tried them in. Based on the current version of your code, you're missing two things:
First, an OleDBConnection object to use with the OleDbDataAdapter.
Second, you're not assigning anything to the DataGridViews DataSource property, so nothing will show up.
Also, you appear to be using two different OleDbDataAdapters (or maybe two different DataAdapters altogether) to fill tblCustomBooks, so depending on what BooksTableAdapter is set up as may also be causing you problems.
Try this:
Private Sub txtTerm_TextChanged() Handles txtTerm.Changed
If Trim(txtTerm.Text) = "" Then Exit Sub
Dim tblCustomBooks As New DataTable
Using conn As New OleDbConnection(connectionString)
Dim adpBooks As New OleDbDataAdapter("SELECT * FROM books WHERE title = 'php%' ORDER BY title", conn)
adpBooks.Fill(tblCustomBooks)
gridTable.DataSource = tblCustomBooks
End Using
End Sub
See:
DataGridView.DataSource Property
OleDbDataAdapter Class
In your SQL statement try [WHERE Title LIKE 'php%'] instead of [WHERE Title = 'php%'].
I've run into similar problems with MS SQL and this was the fix. I'm not sure if the SQL syntax is the same for the Jet provider, but it's worth a try at least.
HTH
dim dt as new datatable
'i already maked the class and now load from a database
dt=cls.getdata("select * from tblinf")
datagridview1.datasource=dt