Recently I want to renew my old application witch is use foxpro 6 to wrote. Now i want to use VB.net to do a new one. The reason behind is that my project is a POS system for my uncle's shop. since the PC is too old that maybe broken anytime, I need to renew it and compatible with Windows 10 because the new PC is using Windows 10. So that's why I need to make a new app But when i use the link services(data source>add new data source) in Visual Studio, it show my table is blank which is wrong, My table is full of data. so how can i successfully link the table to visual studio?
Connection string Dsn=inventory
PS:i use the right odbc driver and test it multiple times and stand still.
Thank You all.
Use VFPOLEDB for connection. With VFPOLEDB, you would simply use an OleDbConnection with a connection string like:
new OleDbConnection("Provider=VFPOLEDB;Data Source=c:\your data folder")
Also check Tom Brother's LinqToVFP, VFP EF Provider and others on codeplex.
IMHO, using windows 10 is not a good reason to rewrite a VFP application in VB.Net. Anyway if you want to do that, then why wouldn't you also change your database backend to something else like postgreSQL, MySQL, SQL Server, ... etc.
I found the solution that you can use code instead of wizard to connect the FoxPro table, here's the solution.
Use a connection string to connect the table first, than set a DataAdapter and DataSet for the table, Finally fill the DataAdapter and put it into the DataGridView.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connectionString As String = "provider=vfpoledb.1;data source=your location"
Dim myConnection As New System.Data.OleDb.OleDbConnection(connectionString)
myConnection.Open()
Dim dataAdapter As New OleDbDataAdapter("FoxPro SQL cmd", myConnection)
Dim dataSet As DataSet = New DataSet
dataAdapter.Fill(dataSet, "Q")
DataGridView1.DataSource = dataSet.Tables("Q")
End Sub
Hope this can help.
Related
Dim cat As New Catalog()
Dim con As New OleDbConnection()
Dim cmd As New OleDbCommand
Dim ds1 As New DataSet
Dim conn As ADODB.Connection
' Open the Access database.
conn = New Connection
conn.ConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" &
"Data Source=" + openExcel + "\Test" + ".mdb; Persist Security Info=False"
con.ConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" &
"Data Source=" + openExcel + "\Test" + ".mdb; Persist Security Info=False"
conn.Open()
xlWorkSheet1.Columns(5).Insert
Dim cellValue As String = ""
Dim newValue As String = ""
Dim sh1 As String = ""
Dim qty As String = ""
Dim matchText As String = ""
Dim sql As String = ""
con.Open()
sh1 = LTrim$(xlWorkSheet1.Cells(i, 1).Text)
sql = "SELECT Num_ber, Q_ty FROM good WHERE Na_me LIKE 'staff%' And Ty_pe = 'ORD'"
Dim cmd As New OleDbCommand(sql, con)
Dim myReader As OleDbDataReader = cmd.ExecuteReader()
conn.Execute(sql)
myReader = cmd.ExecuteReader() ' HERE'S THE PROBLEM
xlWorkSheet1.Cells(1, 5) = myReader.GetString(0)
xlWorkSheet1.Cells(1, 11) = myReader.GetString(1)
myReader.Close()
conn.Close()
conn = Nothing
**I wanted to retrieve a specific value from mdb and then write it to excel.
Here's my code, I got this error so many times and I can't find it out. Can anybody help me? Thanks.**
[1]: https://i.stack.imgur.com/6Fuvg.png
Ok, you first have to decide when usng .net what "provider" you are going to use, AND THEN decide what kind of data objects you want to use.
You can use a oracle provider, a sql server provider, or in this case, since we using Access, then we can use EITHER oleDB, or ODBC. Either choice is fine. Most use oleDB providers for Access, but often ODBC is a good choice, especially if down the road you plane to swap out Access for say SQL server.
What the above means in plain English?
You don't want to adopt the external ADODB code and library. That code is NOT .net, and thus you REALLY but REALLY do not want to write your .net code that way. ADODB was written LONG before .net, and is what we call un-managed code (non .net). I strong, but strong suggest you do NOT add a reference to ADODB to your project, and I beyond strong recommend you avoid introduction of a non .net library for doing this!!! We certainly can adopt the oleDB provider in .net, but we will NOT have a direct reference to JET/ACE (the access database engine) in our applcation. As noted, there are some exceptions to this suggesting, but they don't apply to you and here.
Next up:
The design pattern in .net is to create the connection, get the data, and CLOSE the connection. This "pattern" will then be 100% sure that the data base is always closed, and you NEVER have to worry about if the connection is open, closed, or even if you forgot to close the connection!!! So, do this correct, and some "open" connection will never bite you, or will you have to worry about this issue.
You can in some operations keep the connection open for performance, but lets learn to walk before we run so to speak.
next up:
We certainly do NOT want to place and have connection strings all over in our code. Not only is this going to wear out your keyboard, but if you ever need to change the connection, then you going to have to hunt down all that code.
Best to let Visual Studio save that connection in ONE location, and MORE important MANAGE this for you!!!
Next up:
Do you ONLY need to work with mdb files, or do you plan/need to work with accDB files? This is a HUGE issue, and one that you cannot ignore.
next up:
Are you going to use the x32 bit version of the Access database system, or the x64 bit version?
Since your example posted code uses JET (access data engine for mdb files ONLY x32 bit version)?
Then this ALSO means you MUST (and I repeat MUST) force your .net project to run as x32 bits. You cannot use "any cpu", and you cannot use x64 bits, you MUST choose x86 bit size for your .net project. Failure to do so will result in the project not working.
Ok, with the above information?
First up, force/set/be 100% sure your project is set to run as x32 bits.
That setting is this one:
and remove the reference you have to ADO if you created one.
Ok,
next up:
Create the connection to the database.
Project ->properties.
This here:
And then:
and then
Now, you can browse, and select the access mdb file.
But, you MUST not skip the next step - you have to choose JET (older, mdb files), or choose the newer ACE (for accDB format files).
So, this:
now this:
As noted, you choose JET or ACE here.
now, we have this and you can use test connection.
BUT BE VERY careful!!!!
If you are using vs2022, then keep in mind vs2022 is the FIRST version of VS that is now x64 bits. As a result, vs can't pass the test connection!!! Your connection is in fact ok, but will fail with vs2022.
If you using a previous version of VS (before 2022), then the test connection button should work. and you see this:
Ok, now that we have a valid working conneciton setup, we can now write code, and we will NOT use ADODB!!!!
The typical code pattern to read and load a data table (like a access VBA recordset) will be like this:
Now, I became RATHER tired of writing that same using block over and over. So, in a global module, I have this code now:
Public Function MyRst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using conn As New OleDbConnection(My.Settings.AccessDB)
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
So, now with the above handy dandy helper routine?
Your code becomes this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Sql As String =
"SELECT Num_ber, Q_ty FROM good WHERE Na_me LIKE 'staff%' And Ty_pe = 'ORD'"
Dim rstData As DataTable = MyRst(Sql)
Debug.Print("Na_me is " & rstData.Rows(0).Item("Na_me"))
End Sub
Or, display all return rows from that data table
Debug.Print("Na_me is " & rstData.Rows(0).Item("Na_me"))
For Each OneRow As DataRow In rstData.Rows
Debug.Print("na_me = " & OneRow("Na_me"))
Next
So, you really don't need (or want) a reader anyway. Just load the results into a nice clean, easy to use data table, and from that you can loop the table, grab rows, or do whatever you want.
A little background first. Where I work we have limited access to programming tools. We have access to the Microsoft Office Suite and therefore most of our projects are created in Access even though there are better solutions out there. We recently received access to Visual Studio 2013 and I am interested in converting some of our more heavily used tools into VB.NET projects.
I have a good understanding of VBA after using it for so many years, however, converting to VB.NET is definitely a change and although I understand the concept of it, many of the functions I used in the past do not exist in VB.NET.
Which leads me to the following question.
How do I connect to one database, an ODBC connection, then put selected fields from a table in that database to a table in a Microsoft Access database?
Here is my current code.
Imports System.Data.Odbc
Imports System.Data.Odbc.OdbcCommand
Imports System.Data.OleDb
Public Class Form1
Dim conn As OdbcConnection
Dim connBE As OleDb.OleDbConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Call Connect_SLICWave()
Call Connect_Backend()
Dim sqlInsert As String = "INSERT INTO tblUOCs (EIAC,LCN,ALC,UOC) SELECT DISTINCT Trim(EIACODXA),Trim(LSACONXB),Trim(ALTLCNXB),Trim(UOCSEIXC) FROM ALAV_XC"
Dim beCmd As New OleDb.OleDbCommand(sqlInsert, connBE)
beCmd.ExecuteNonQuery()
End Sub
Private Sub Connect_SLICWave()
Dim connectionString As String
connectionString = "Dsn=slic_wave;uid=userid;pwd=password"
conn = New OdbcConnection(connectionString)
End Sub
Private Sub Connect_Backend()
Dim connectionStringBE As String
connectionStringBE = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\database.accdb"
connBE = New OleDb.OleDbConnection(connectionStringBE)
End Sub
End Class
Clearly this is not going to work. I have tried a few things based on examples on the Internet but have been unable to piece together any kind of code that works.
When using the Access database I would simply link to the tables in both the ODBC connection and the backend Access database and then I could use DoCmd to run SQL to move data as needed, however with VB.NET I don't have that luxury. Perhaps I am going about this all wrong due to my lack of knowledge with Visual Studio.
Is there a better way to accomplish my end goal? I need to be able to refer to the data in the ODBC connection and then store it somewhere so that I can output a specific dataset to the end user. Can/should I use a DataSet or DataTable? How much data can be stored in a DataSet/DataTable before the program would become unstable? The data used in this process can be quite excessive at times.
Typically the user would send the tool some criteria with 4 or 5 fields worth of data. The tool will then turn around and take that criteria to get the proper dataset from the ODBC connected database using joins on about 5 to 7 tables and returns one set of data to the user. Yes, it is a bit excessive, but that's the requirement.
I hope I am explaining this well enough without being too generic. The nature of my business prevents providing specific examples.
Sorry for being longwinded and I appreciate any effort that goes into helping me solve this issue. If there is anything that needs to be clarified please let me know and I will try to explain it more clearly.
You may find it helpful to be aware that when you run a query against the Access Database Engine from a .NET application you can use ODBC references in your queries and the engine will perform the required ODBC connections for you. In effect, these are temporary "on the fly" ODBC linked tables created for that specific query.
Say we have a table named [product] in SQL Server
id name
-- -----
1 bacon
2 tofu
and we can reach that SQL Server instance via an ODBC DSN named "myDb". We can reference that table from an Access query as
[ODBC;DSN=myDb].[product]
So, for example, if we want to query an Access table named [Orders]
OrderID ProductID Qty Units OrderDate
------- --------- --- ----- ----------
1 1 3 pound 2016-10-17
and pull in the product names from the SQL Server table named [product] we can do this in VB.NET:
Dim myConnectionString As String =
"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\Users\Public\Database1.accdb;"
Using conn As New OleDbConnection(myConnectionString)
conn.Open()
Dim sql As String =
"SELECT p.name, o.Qty, o.Units " +
"FROM " +
"Orders o " +
"INNER JOIN " +
"[ODBC;DSN=myDb].[product] p " +
"ON p.id = o.ProductID"
Using cmd As New OleDbCommand(sql, conn)
Using rdr As OleDbDataReader = cmd.ExecuteReader
While rdr.Read
Console.WriteLine("{0} {1}(s) of {2} ", rdr("Qty"), rdr("Units"), rdr("name"))
End While
End Using
End Using
End Using
which prints
3 pound(s) of bacon
First of all, I need to ask about the original source for your SLICWave ODBC connection. Is it still in Access, or are you perhaps pulling from Sql Server or similar at this point? ODBC is going to pass your command statement on to the original source, and if you're using Sql Server now, instead of Access, some of the SQL syntax will change on you.
For the remainder of the question, I'll assume the SQL you have will work if executed. If it turns out you need help converting that to T-SQL for SQL Server, open a separate question limited to that specific problem.
That out of the way, I'm now going to limit my scope to this statement:
I need to be able to refer to the data in the ODBC connection and ... output a specific dataset to the end user.
What you want to do is put a DataGridView control on your form (I'll use the default DataGridView1 name for now). Then make the form code look like this:
Imports System.Data.Odbc
Imports System.Data.Odbc.OdbcCommand
Imports System.Data.OleDb
Public Class Form1
Private Property SLICWaveConnectionString As String = "Dsn=slic_wave;uid=userid;pwd=password"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim sql As String = "SELECT DISTINCT Trim(EIACODXA),Trim(LSACONXB),Trim(ALTLCNXB),Trim(UOCSEIXC) FROM ALAV_XC"
Dim dt As New DataTable
Using cn As New OleDb.OleDbConnection(SLICWaveConnectionString), _
cmd As New OleDb.OleDbCommand(sql, cn)
da As New OleDb.OleDbDataAdapter(cmd)
da.Fill(dt)
End Using
DataGridView1.DataSource = dt
End Sub
End Class
Imports System.Data.OleDb
Public Class Form1
Public con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\stores\Stock.accdb")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.Open()
Dim sql As String = "SELECT * FROM Stock"
Dim dt As New DataTable
Dim cmd As New OleDbCommand(sql, con)
Dim da As New OleDbDataAdapter(cmd)
da.Fill(dt)
DGV.DataSource = dt
con.Close()
End Sub
End Class
I have a weird problem: I'm trying to do some basic procedure to insert data in a database and I don't know what it's happening, but it does not work.
The thing is that I have a database called prova3 that is a SQL Server 2012 database created with vb.net 2013 with a table called tabela. I created a dataset to see the connection string that is stored in app.config. The string is the same below. I'm not getting an error, but the data is not inserted. When I go to the Server explorer to see the data in the table, it's empty.
I think the data it's been saved in elsewhere, but I don't know how to fix it, because I think I'm coding this right. This is for vb.net, but I did the same code for asp.net and it works. Weird.
Could you help me?
In the form it's only a textbox1 and a button1 controls. There is no more code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ImageUrlSt As String
Dim command1 As New SqlCommand
Dim con As New SqlConnection
ImageUrlSt = TextBox1.Text
Try
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Prova3.mdf;Integrated Security=True"
con.Open()
command1.Connection = con
command1.CommandText = "INSERT INTO Tabela (imageurl) VALUES (#imageurlst)"
command1.Parameters.Add(New SqlParameter("#imageurlst", ImageUrlSt))
command1.ExecuteNonQuery()
MsgBox("News Saved Succesfully")
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Sometimes |DataDirectory| as path is problematic when debugging. Did you check the db copy at \bin\debug?
There’s a property Copy to Output Directory and the default value is Copy if newer (if you’re using .mdf or .mdb file, the default value is Copy always). You could check this MSDN document to learn what this property means. In short, the local database file will be copied to Output directory, and THAT database is the one that will get updated.
If you don’t want Visual Studio to copy the database file for you, you could set the Copy to Output Directory property to Do not copy. Then it’s your choice when and how to overwrite the database file. Of course, you still need two copies of database file: at design time, you’re using the database file in solution directory, while at run time, you’re modifying the one in output directory.
Another option is to use an absolute path at ConnectionString like
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\MyProjectFolder\Prova3.mdf;Integrated Security=True"
I have been searching for a couple hours, and found several questions, but none of them really explained this in a way I can understand.
I'm programming a game similar to Rock Paper Sissors, except with many more selections, and the possiblity of a tie. I had originally hardcoded all of the possible outcomes, then decided to try a database so I can learn and practice sql as well.
Problem is, I can't figure out for the life of me how to connect to my local database, now that I have set it up and filled it through Visual Studio 2010. I can connect to it through Server Explorer just fine, and I can see it in Solution Explorer. I've tried several things, along the lines of:
Private sqlConn As New SqlConnection("Data Source=(local)|DataDirectory|\Outcomes.sdf;database=Outcomes;Integrated Security=true")
Private sqlConn As New SqlConnection("Data Source=.\SQLEXPRESS; Integrated Security=true")
Dim sqlConn As SqlConnection
sqlConn = New SqlConnection("DataSource=..\..\Outcomes.sdf")
I am relatively new to sql, but know enough through tinkering to build a sql statement and get me the result I want. But I've never connected to a database before. I've looked on MSDN and tried several things I saw on there (everything that looked like what I needed, really) but it still hasn't worked.
If I can connect, I already have my statement set, and have tested it through the database itself. Any help would be wonderful, especially if it's explained in a way I can understand it and use it for later.
Also, if it helps and isn't noticed through my tried code, my db name is Outcomes. I don't know if that is needed or will help, but just in case.
Please visit connection strings here...
It also would have been helpful to know what type of DBMS you are using as well. I noticed you have an .sdf database file, not a DBMS (For ex: MySql, SQL or Oracle). Therefore, your connection string is really going to depend on what you want.
Your issue is here by the way...
Private sqlConn As New SqlConnection("Data Source=(local)|DataDirectory|\Outcomes.sdf;database=Outcomes;Integrated Security=true")
*You cant use the SqlConnection you have because its not supported with the use of .sdf files.
Instead you have to use: System.Data.SqlServerCe 'This is for compact edition
If you would like to know more about this please see here.
Kendra,
Here are the logical Steps you will need to follow to access the database programmatically:
Note: I'm assumming you have the proper SQLExpress | SQL Server Database setup whether local or remote the methods below are identical except for the connection string information.
1) Import the Sql AdoNet Namespace so you can use the proper SQL Server Client Objects & Methods;
a) Imports System.Data.SqlClient
2) Establish a Connection to the database with the ADO Connection Object:
' Create your ADO Connection Object:
Private myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes;" & _
"Data Source=localhost;Integrated Security=SSPI;")
Note: This connection string uses integrated security from your windows machine. you could also use standard security where you would need to enter your username and password credentials. Its your choice.
3) Setup Your ADO Command Object to Define your data retrieval query:
'Create a Command object.
Private myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT FirstName, LastName FROM Employees"
'Open the connection.
myConn.Open()
Note: Subsitute CommandText string for your actual query based upon your own database schema.
4) Read, Fetch, Display Data using the SQLDataReader Object:
Private results As String
Private myReader As SqlDataReader
myReader = myCmd.ExecuteReader()
'Traverse the DataSet and Display in GUi for Example:
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab & _
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)
5) Gracefully Close all Objects Used:
' Close the reader and the database connection.
myReader.Close()
myConn.Close()
Note - You'll need to consult microsoft for further connection string formats, since I don't have enough info. But this should clarify the actual big picture steps for you.
Regards,
Scott
VB express 2010
1 form, 1 textbox , 1 button
I created the .mdf sql database file by clicking Project>add new item>service based database> and named it DXDB - table name DXtest and 1 column named test
It seems like the codes works..however when I right click DXtest and click show table data... there is nothing there... =( It seems like it doesnt really insert the data on the database itself...
Here is the complete code
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Tx1 As String
Tx1 = TextBox1.Text
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DXDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO DXTest(Test) VALUES(#Tx1)"
cmd.Parameters.Add("#Tx1", SqlDbType.VarChar, 50).Value = Tx1
cmd.ExecuteNonQuery()
con.Close()
End Sub
End Class
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. DXDB)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\SQLEXPRESS;Database=DXDB;Integrated Security=True
and everything else is exactly the same as before...