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
Related
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 :)
I've added an access db to my project as a datasource. So I get the automatically generated tableadapters class and therefore, access to the table adapter instance which includes the connection string. I'm using this to open a connection to my db so I can first, delete some records, and then replace them with new records.
The queries seem to work because the .executenonquery does return the rows affected. I even tried a delete * command to be sure. But, when I open the database everything is the same.
I had some ideas as to why. I thought the connection string returned by the tableadapter might be goofy because it contains a generic pointer to the project's data directory.
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DupeMDB.mdb;Persist Security Info=True
I also thought maybe I had a problem with the Build Action or the Copy to Output Directory. I really don't understand the mechanics behind these two things. I think maybe the copy to output directory thing might be the culprit.
Here's me goal. I want to deploy this project to my secretary so she can use the program to deal with a duplicate record list etc. The data has to go with the program. I want to package this .mdf file with the deployment and get it back from her when she's done with it. I am so close to the end here (writing back to the table). Does anyone know why the table won't update?
Dim Connector As DupeTblTableAdapter = New DupeTblTableAdapter
Dim Conn As New System.Data.OleDb.OleDbConnection
Conn = Connector.Connection
Conn.ConnectionString = Connector.Connection.ConnectionString
MsgBox(Conn.ConnectionString)
Dim Comm As System.Data.OleDb.OleDbCommand
Conn.Open()
For Each DR In DeleteRecords
Comm = New System.Data.OleDb.OleDbCommand($"DELETE from DupeTbl where DupeTbl.CUST_NO={DR.ToString}", Conn) '
Dim aff As Integer = Comm.ExecuteNonQuery
'MsgBox(aff)
Comm = Nothing
Next
For Each RR In ReplaceRecords
Comm = New System.Data.OleDb.OleDbCommand($"INSERT INTO DupeTbl ( CUST_NO, PREDIR, POSTDIR, SUFFIX, CUSTSIZE, AddFlag, IgnoreRecord ) VALUES ({RR.Cust_No}, '{RR.PreDir}', '{RR.PostDir}', '{RR.Suffix}', {RR.Size}, {RR.AddFlag}, {RR.Ignore});", Conn)
Comm.ExecuteNonQuery()
Comm = Nothing
Next
Conn.Close()
The issue in such cases is usually the working database being overwritten on each build. When adding a local data file to your project, it is added as a source file in the project folder. By default, the Copy to Output Directory property is set to Copy Always. That means that every time you build your project, which will happen each time you make a code change and run the project by default, the source file will be copied over the top of the working database in the output folder, thus wiping out any changes you made while debugging. To prevent this, change that property to Copy if Newer, which means that the working database will only be overwritten if you make a change to the source database, e.g. modify the schema.
Dim Connector As DupeTblTableAdapter = New DupeTblTableAdapter
Dim Conn As New System.Data.OleDb.OleDbConnection
Conn = Connector.Connection
Conn.ConnectionString = Connector.Connection.ConnectionString
MsgBox(Conn.ConnectionString)
Dim Comm As System.Data.OleDb.OleDbCommand
Conn.Open()
For Each UR In UpdateRecords
Comm = New System.Data.OleDb.OleDbCommand($"UPDATE DupeTbl SET CUST_NO = <NewValue>, PREDIR = <NewValue, POSTDIR = <NewValue> etc. where DupeTbl.CUST_NO={DR.ToString}", Conn) '
Dim aff As Integer = Comm.ExecuteNonQuery
'MsgBox(aff)
Comm = Nothing
Next
Conn.Close()
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
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.
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.