SQL INSERT Command from Visual Studio - sql

I am having a problem with an INSERT statement from Visual Studio actually inserting records into the table
The statement is:
Dim cmd As New System.Data.SqlClient.SqlCommand
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "INSERT Document (CompanyName) VALUES ('Code Test SUCCESS')"
cmd.Connection = sqlConnection1
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
The problem I think is with:
"INSERT Document (CompanyName) VALUES ('Code Test SUCCESS')"
In the Document table there are only two columns:
DocumentID (Primary Key, auto incrementing)
CompanyName
The application runs fine doesn't throw any errors but the data will not appear as a new record.
Many thanks in advance.
EDIT: The connection String is
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PostTracker.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

You use DataDirectory substitution string for your connection. So, if you don't have any error then the record is inserted but it is not in the database that you are looking at.
In WinForms applications, the DataDirectory is replaced using the working directory of your application. This working directory, inside a debug session of Visual Studio, is PROJECTFOLDER\BIN\DEBUG (or x86 variant).
If you check your data using Server Explorer inside Visual Studio chances are that the connection string used by Server Explorer points to the MDF file located in the PROJECTFOLDER where no record has been inserted.

Related

Can't insert data into access database using vb 2010

I have a little problem with my coding. there's no error when I'm running the program. But, I can't insert the data into my access database. Actually, I have the same problem with Update/editing data. I'm working with Visual basic 2010
Dim con As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=dbBantuDong.accdb;"
con.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = con
cmd.CommandText = "INSERT INTO tbCounter VALUES ('Corp',1,3)"
cmd.ExecuteNonQuery()
MsgBox("Success")
Click on your database file on the Solution Explorer of your project. In the properties window, you can see Copy To Output Directory property.
There are three options available:
Select Do not copy if the file is never to be copied to the output directory.
Select Copy always if the file is always to be copied to the output directory.
Select Copy if newer if the file is to be copied only when it is newer than an existing file of the same name in the output directory.
Make the change accordingly. Hope this helps :)

Can't save data to SQL Server database

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

VB 2013 Access DB Dataset

Rewriting a legacy system in VB 2013 Express which connects to an Access DB. I've set up the Data Connection and have a DataSet with all the tables. The code needs to do the following:
Delete all the rows in the "extract" table;
Read in and parse the new data;
Write the new data to the "extract" table.
I've got the reading and parsing part done, but I need help with the deleting and writing part. Nothing I try seems to work.
This is what i've tried:
Dim sqlConnection1 As New System.Data.SqlClient.SqlConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\CLI_CRVM.accdb")
Dim cmd As New System.Data.SqlClient.SqlCommand()
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "DELETE FROM extract"
cmd.Connection = sqlConnection1
You are trying to use System.Data.SqlClient, but that is specifically for working with Microsoft SQL Server databases. The example code in your question will fail with
Keyword not supported: 'provider'.
For an OLEDB connection to your Access database, use System.Data.OleDb.

Can't Insert data to database ms-access vb

Case 1: i can't insert data to my database
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ProjectVB.accdb")
Case 2: i can insert data to my database
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Admin\Documents\ProjectVB.accdb")
database was saved in my project already
conn.Open()
cmd.Connection = conn
cmd.Parameters.AddWithValue("#ac_ID", txtID.Text)
cmd.Parameters.AddWithValue("#ac_pass", txtPassword.Text)
cmd.Parameters.AddWithValue("#nation_ID", txtNoID.Text)
cmd.Parameters.AddWithValue("#fName", txtFirstName.Text)
cmd.Parameters.AddWithValue("#lName", txtLastName.Text)
cmd.Parameters.AddWithValue("#tel", txtTel.Text)
cmd.Parameters.AddWithValue("#province", cbNation.SelectedItem)
cmd.Parameters.AddWithValue("#regOn", dtRegOn.Text)
cmd.Parameters.AddWithValue("#status", txtStatus.Text)
cmd.Parameters.AddWithValue("#gender", cbGender.SelectedItem)
cmd.Parameters.AddWithValue("#location", txtLocation.Text)
cmd.Parameters.AddWithValue("#img", imgBuffer)
cmd.Parameters.AddWithValue("#rank", cbRank.SelectedItem)
cmd.CommandText = "INSERT INTO db_KJ_Profile VALUES(#ac_ID,#ac_pass,#nation_ID,#fName,#lName,#tel,#province,#regOn,#status,#gender,#location,#img,#rank)"
cmd.ExecuteNonQuery()
In the case of the DataDirectory substitution string you should check the content of the database in the folder PROJECTFOLDER\BIN\DEBUG (or x86 version of the same path).
This is due to the fact that in a WinForms application, when running in a debug session of VS, the DataDirectory points to the folder where your application is executed (The BIN\DEBUG or BIN\x86\DEBUG subfolder of the project folder).
This is easy to overlook and it is always a source of confusion.
And it is worse if you have the ACCDB file listed in your project items. In this case the database item has a property called Copy To The Output Directory. You should check that is set to Copy If Newer or Copy Never and not to Copy Always because in this case, at every restart of your debug session a new copy of the database is copied (of course without the just inserted data) from your project folder to the BIN\DEBUG folder

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.