Can't save data to SQL Server database - sql

I'm quite confused why the data that I added was not saved to the database.
While my program is running there are no problems in updating the data that is shown in DataGridView but when I close the program, the added data disappears.
I tried to show table data but there were no new data added. Can you tell me what is the problem?
This is my code:
Dim con As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand
Dim adaptor As New SqlClient.SqlDataAdapter
Dim dataset As New DataSet
con.ConnectionString = ("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True")
con.Open()
cmd.CommandText = "INSERT INTO [Table](FirstName,LastName,MI,Address,Email) VALUES(#FN,#LN,#MI,#AD,#EM)"
cmd.Connection = con
cmd.Parameters.Add("#FN", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#LN", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#MI", SqlDbType.VarChar).Value = TextBox3.Text
cmd.Parameters.Add("#AD", SqlDbType.VarChar).Value = TextBox4.Text
cmd.Parameters.Add("#EM", SqlDbType.VarChar).Value = TextBox5.Text
cmd.ExecuteNonQuery()
MsgBox("Added!")
con.Close()
Me.TableTableAdapter.Fill(Me.Database1DataSet.Table)

The whole 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 create your database on the server using a management tool (like SSMS Express), give it a logical name (e.g. MyDatabase), and then connect to it using its logical database name (given when you create it on the server). 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=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Betrand's blog post Bad Habits to Kick - using AttachDbFileName for more background info

Related

Setting Up SqlConnection string in vb.net for a local database created through visual studio 2010

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

Opening SQL connection

I have inherited software to maintain. The previous version used a third party Datagridview substitute that isn't compatible with versions of Windows from Vista on. In attempting to put Datagridviews in I have run into a problem with connecting to the database.
I am trying to make a small program to play around with connection and SELECT outside of the original software so I can further understand what I am doing and without going through the full process of using the original software to get to the testing point.
Private Shared Function GetData(ByVal sqlCommand As String) As DataTable
Dim table As New DataTable()
Dim connectionString As String = "Data Source=.\SQLExpress;Integrated Security=true;" _
& "AttachDbFilename=C:blah\blah\blah.mdf;User Instance=true;"
Using con = New SqlConnection(connectionString)
Using command = New SqlCommand(sqlCommand, con)
Using da = New SqlDataAdapter(command)
da.Fill(table)
End Using
End Using
End Using
Return table
End Function
My SQL command is a simple "Select * FROM Setup" and the rest of the program is form loads, imports, and DataGridView formatting. I don't think it affects the SQL part and would be cumbersome to include here.
This results in what appears to be a closed connection.
![Connection Property] http://i.imgur.com/b5V3Qy5.png
This is a screenshot of my SQLExpress which might help diagnose connection problems.
![SQL Properties] http://i.imgur.com/bakBq5D.png
I've blurred out the computer name in grey, but I did notice that there was another computer name in pink. I don't know what it means other than maybe this database was originally created on another computer and has been copied and pasted.
Finally this is the connection string that the original software used:
"Data Source=.\SQLExpress;AttachDbFilename=C:\blah\blah\blah.mdf;Trust_Connection=Yes;"
I have also tried:
"Data Source=.\SQLExpress;AttachDbFilename=C:\blah\blah\blah.mdf;Trusted_Connection=Yes;User Instance=true"
Finally, this is my exception:
"An attempt to attach an auto-named database for file C:\blah\blah\blah.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
I got my alternate connection strings from www.connectionstrings.com.
You are missing the Open() command.
con.Open()
Full code listing. (Also a good idea is to wrap your code in a Try.... End Try block).
Private Shared Function GetData(ByVal sqlCommand As String) As DataTable
Dim table As New DataTable()
Dim connectionString As String = "Data Source=.\SQLExpress;Integrated Security=true;" _
& "AttachDbFilename=C:blah\blah\blah.mdf;User Instance=true;"
Using con = New SqlConnection(connectionString)
conn.Open()
Using command = New SqlCommand(sqlCommand, con)
Using da = New SqlDataAdapter(command)
da.Fill(table)
End Using
End Using
End Using
Return table
End Function

Restoring a backup using SQLCommand in VB.NET

I've got a VB.NET console application I'm creating that will make it easier for people to work with some test databases, and part of this is having a function that restores the database. I thought it was fairly straightforward, and here is the code I have so far:
Sub Restore()
con = New SqlConnection("Data Source=" & utilnamespace.sqlSvr & ";Database=Master;integrated security=SSPI;")
cmd = New SqlCommand("ALTER DATABASE [db] SET OFFLINE WITH ROLLBACK IMMEDIATE RESTORE DATABASE db FROM DISK = 'G:\db.bak' WITH REPLACE, STATS = 10", con)
cmd.Connection.Open()
cmd.ExecuteNonQuery()
Console.WriteLine(cmd.CommandText)
cmd.Connection.Close()
End Sub
The SQL works fine if I run it in SSMS, however it will time out if I try to run it from the app. The problem is that I've read over this and I'm still unsure of what to do.
Should I use BeginExecuteNonQuery and then have it listen for the statement complete message somehow?
Even if I believe that showing a waiting form and waiting for some kind of confirmation would be better for the end user... have you tried changing the timeout in the connection string to solve it in a quick way?
eg (seconds):
string connStr = "Data Source=(local);Initial Catalog=db;
Integrated Security=SSPI;Connection Timeout=30";
Also check these links:
SQL Server Management Objects (SMO)
SQL Server 2008 - Backup and Restore Databases using SMO
If the database is too big you can increase the timeout of the Command, not the connection string
cmd.Connection.Open()
cmd.CommandTimeout = 100
cmd.ExecuteNonQuery()
Console.WriteLine(cmd.CommandText)
cmd.Connection.Close()

Cannot connect to dbf file

I'm trying to connect to to a foxpro table (.dbf) from a test vb.net form.
I recieve an OleDbException with the message "Cannot open file c:\emp\emptbl.dbf"
Have tried with both of the following connection strings:
Provider=VFPOLEDB.1;Data Source=C:\emp\emptbl.dbf
from the MSDN article here
Provider=vfpoledb;Data Source=C:\emp\emptbl.dbf;Collating Sequence=machine;
from connectionstrings.com
The latter seems to be the type to use when connecting to a single table, but the same exception is thrown regadless of which is used.
I can open and perform the same query okay in visual foxpro 6.0.
Here's my code:
Dim tbl As DataTable = New DataTable()
Using con = New OleDbConnection(conString)
cmd = New OleDbCommand() With {.Connection = con, .CommandType = CommandType.Text}
Dim sSQL As String = "SELECT * FROM(EMPTBL)"
cmd.CommandText = sSQL
Dim adp As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
con.Open()
adp.Fill(ds)
con.Close()
If (ds.Tables.Count > 0) Then
tbl = ds.Tables(0)
End If
End Using
Return tbl
The OleDB provider should only connect to the PATH where the tables are... not the actual file name. Once you connect to the PATH, you can query from ANY .Dbf file that is located in it
Provider=VFPOLEDB.1;Data Source=C:\emp
select * from emptbl where ...
You can also look at other connection string settings at
ConnectionStrings.com
UPDATE per comment.
It appears you are getting closer. with your attempt without the () parens. In VFP, within parens, it interprets that as "look for a variable called EMPTBL", and from its value is the name of the table to query from. Not something you would need to apply via OleDB connection.
Now, cant open the file is another. Is it POSSIBLE that another application has the table open and the file is in exclusive use? and thus can not be opened by the .net app too? Even for grins, if you open VFP, and just do a simple create table in the C:\Emp folder and put a single record in it, then you know no other program will be using it as it is a new file. Quit out of VFP and try to query THAT table. There should be no locks, no other program is expecting it, so it should never be opened by anything else and you should be good to go.

ADO.Net Synchronization & SQL CE

I've succesfully synchronized both source and local db using the local database cache item in VS 2008.
However, I need to access the SQL CE db directly from within another dll/process, and without using a dataset. The reason being that my business object code does not use datasets.
The final code wouldlook something like this:
Dim conn As New SqlServerCe.SqlCeConnection("Data Source=C:\Development\UserDirectory\UserDirectory.DBSyncher\ProfDir.sdf;Persist Security Info=False;")
Dim cmd As New SqlServerCe.SqlCeCommand("Select EmailAddress from Employees Where ID=23", conn)
Dim returnString As String = ""
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
returnString = cmd.ExecuteScalar
conn.Close()
cmd = Nothing
I notice something very strange using a dataset the synchronized changes are shown but accessing the CE database file directly returns old data - no synched data whatsoever.
What am I missing? Any help would be greatly appreciated.
Figured it out!
Forgot that CE is in process, thus it copies the database file(.sdf) to the Debug folder. You have to to reference that database not the one in your project. DOH!