Insert data on SQL Table... cannot find the data - sql

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...

Related

Can't access Local SQL database manually by connection string in VB.NET using Visual Studio

I have a project set up with 3 separate tables. I used the built-in designer from Visual Studio.
The tables contain
Students
Courses
Tests in each course
All the tables share a studentnumber.
I have no problem getting and accessing the data true different tableadapters and corresponding bindingsources automatically generated by Visual Studio when I "drag and drop" them on the forms. I also am able to use the query builder to get the data I need from each table.
My problem occurs when I try to access the database manually via connection string.
I get this error:
Cannot attach file local path\HovedDatabase.mdf as database Outcomes because the file is already in use for database local path\HovedDatabase.mdf
This is the code I have:
Private Sub FormPrøver3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'StudentDataSet.StudentTabell' table. You can move, or remove it, as needed.
Me.StudentTabellTableAdapter.Fill(Me.StudentDataSet.StudentTabell)
Me.StudentTabellTableAdapter.Connection.Close()
Get_Data_Manualy_Fag()
End Sub
Private Sub Get_Data_Manualy_Fag()
Try
'Create variabals for inputcontainer
Dim Studnr As String = Me.StudentnrLabel1.Text
'Create a connection to the DataBase
Dim myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes;Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\HovedDatabase.mdf;Integrated Security=True")
'Create a Command object.
Dim myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT Fag FROM Fag3Tabell WHERE Fag = #Studnr"
myCmd.Parameters.AddWithValue("#Studnr", Studnr)
'Open the connection.
myConn.Open()
'Process the answer
Dim myreader As SqlDataReader
myreader = myCmd.ExecuteReader
'Traverse the DataSet and Display :
Dim i As Integer = 0
Do While myreader.Read()
Me.ComboBox1.Items.Add(myreader.GetString(i))
i = i + 1
Loop
'Close the connection
myConn.Close()
'Handle errors
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I set up a similar project with a similar LocalSQL database. I have done nothing in Visual Studio other than creating the database with the same tables.
Here I have no problem connecting to the database via manual connection string.
My question is: why can't I access the local DB with a connection string in the first project?
You haven't posted your other connection string, but it looks like AttachDbFilename may be the problem. The DB will already be attached, this option is only meant to be used in single-user mode (one connection only).
Best bet is to permanently attach the DB to the LocalDB instance if that is what you are using the whole time.

How to connect to SQL Server database with Visual Studio (Windows authentication)

It's been a while since I programmed with Visual Studio (Visual Basic) and SQL Server, and I wanted to get back into it.
I've created a database named LOTTERIE and on my form I inserted a DatagridView which I linked my .mdf database file to see all my data on it.
So far it worked.
But I want to be able to add or remove data with a button. In order to do so, I have to make a connection to my db and make query.
I have installed SSMS and created a local DB which the .mdf was created on C:\Users\Amenard, but then copied in C:\Users\Amenard\source\repos\Projet1 in Visual Studio when I created my project.
I can connect to my database in SSMS with Windows authentication with no problems.
But I cannot create a connection from Visual Studio in my code to make it work.
Can someone guide me how to do it? And also, I'm connected on a domain that I will call for example SAQ.
Here's my code:
Imports System.Data.SqlClient
Public Class Form1
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim dr1 As SqlDataReader
Dim ra As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: cette ligne de code charge les données dans la table 'LotterieDataSet.Tirage'. Vous pouvez la déplacer ou la supprimer selon les besoins.
Me.TirageTableAdapter.Fill(Me.LotterieDataSet.Tirage)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
myconnection = New SqlConnection("server=(LocalDb)\MSSQLLocalDB;uid=SAQ\Amenard;pwd=screen$;database=C:\USERS\AMENARD\SOURCE\REPOS\PROJET1\BIN\DEBUG\LOTTERIE.MDF")
'you need to provide password for SQL Server
myconnection.Open()
mycommand = New SqlCommand("insert into Tirage([date_tirage],[case_1],[case_2],[case_3],[case_4],[case_5,[case_6],[case_7]) values ('2019-01-01','1','2','3','4','5','6','7')", myconnection)
mycommand.ExecuteNonQuery()
myconnection.Close()
End Sub
According to your description, you want to connect DB in the Visual Studio.
First, you need to choose Tools->Connect to Database->Microsoft SQL Server->Copy the Server Name from ssms and paste into the combox->choose windows authentication->select or enter database name->click ok.
Second, you could open view-> SQL server Object Explorer-> choose the correspond server name-> choose the database->right click properties->choose the connection string-> copy the connection string.
Finally, you can try your code to connect to your database in visual studio.

How to insert foxpro 6 table to visual studio 2017?

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.

Select data from an ODBC connection into a MS Access database

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

Inserting Data in sql database vb.net is not getting stored

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"