This feels like a dumb question but I am a bit confused. I am building a C# address book application (Windows Form) that adds, deletes, selects, and updates contacts to an Access database and I'm using DataGridView in the application to show the contacts. I follow the easy steps in connecting to an access database using the wizard, which is Add New Data Source --> Database --> DataSet, then for the Data source I use Microsoft Access Database File (OLE DB), and for the Database FileName, I pick a file on my computer, as shown below.
Now I am confused, because I have to present this on another computer?? Obviously, it won't have the same file address as the one I circled for my computer. Is there a different way to do this or something, I'm not sure what to do. I've heard something about mdb files, but I just have to run the executable file on their computers, so I don't know... I use Access 2016, but the computer I am presenting on uses 2013. Thanks
Okay, nevermind. I found out that I can simply edit the connection string code. I have to test it once in visual studio, then it works appropriately.
public Form1()
{
InitializeComponent();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Chris\Documents\mydb.accdb;
Persist Security Info=False;";
}
to
public Form1()
{
InitializeComponent();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\OtherComputer\Desktop\mydb.accdb;
Persist Security Info=False;";
}
Maybe you can put access DB file(.accdb) to your WebSite or Project.
and Database file name :
~/Book_Sample/Access_db1.mdb
If you use Access 2007~2013 (.accdb)
You need to install "Microsoft Access Database Engine Redistributable"
http://www.microsoft.com/en-us/download/details.aspx?id=13255
Related
I have a simple data entry Windows Form with a datagridview display that links to a local database. When I run the program and try to add data on another computer, I get this message:
Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.
An attempt to attach an auto-named database for file C:\Users\roberto.yepez\Documents\Visual Studio\2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
The file path is to the path on the computer where I coded the program.
Here is my code:
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True".ToString());
I am a self-taught coder, please help! :)
I believe you're running into a problem because your local sql server to which your code is trying to attach the StudentInfo1.mdf (whose path is in the connection string) already contains a database called StudentInfo1 - it decided to try and create a database of this name based on the name of the mdf file. I'm guessing that you can pick your own name by specifying Initial Catalog in your connection string but this would mean there are two databases with possibly the same set of tables and a potential for confusion
Per the comment I posted I would instead advocate that you use SQL Server Management Studio to permanently attach your db (you make have already done this) and then adjust your connection string so that it refers to the permanently attached db. This reduces the chances that your next question will be "my code says it's updating my db but I cannot see any changes!?"
Please move this connection string
"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True"
to app.config file. When you deploy to production, change the paths in that app.config, according to the production machine settings.
You can even apply transformations on the app.config to deploy in various machines/scenarios.
I am creating a application and I want to use a local database stored on the clients local machines. I am debating over if I should use SQLITE or is there something in Visual Studio to help me. The other thing is that I want to create the database programmatically in the users directory when the application is launched.
I am see a few things online but the articles were all about SQL Server stuff and that is not want I want to do with this application. All data will need to be stored on the local machine.
You can use SQL Server Compact, which has tooling in Visual Studio. It's syntax-compatible with SQL Server, but stores its data in a local file, which you can create on the fly (at app startup, for example).
You can create the SQLite database on the fly with the libraries provided from their website. I have used it in many projects for my personal code, as well as it being used in some of the internal architecture of Data Explorer (IBM Product). Some sample C# to create a database file:
if (!Directory.Exists(Application.StartupPath + "\\data"))
{
Directory.CreateDirectory(Application.StartupPath + "\\data");
}
SQLiteConnection conGlobal;
if (!File.Exists(dbGlobal))
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";New=True;Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
firstRun = true;
}
else
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
}
try
{
conGlobal.Open();
}
catch (Exception)
{
//do stuff
}
Simply initiating a connection to the file will create it if the new=true is passed as the connection string. Then you can query it and get results just like you would any database.
You also have the ability to password protect the database files to prevent access to them from just opening them with an SQLite-Shell or a different SQLite DB viewer.
For more info on the pragma statements that are being passed in the connection string, see the following: http://www.sqlite.org/pragma.html
I'm not sure about programmatically (that's probably what you meant, right?) creating the database, but SQL Server Compact Edition has served me well in the past for simple apps. It's embedded and even runs in medium trust.
Context
My appliction uses an SQL database from which it reads my datatables at start of my application. If the application would fail to connect to the SQL DB, I have a local Ms Access .MDB file. I have a separate thread that checks if the local database is outdated.
I have a DataTable which I obtain from my SQL connection --> Verified and working
I can connect to my Access database locally and read from it --> Verified and working
Issue/Question
I'm trying to update my local database by updating it with the DataTable I obtained from my SQL Connection.
public static void UpdateLocalDatabase(string strTableName, OleDbConnection MyConnection, DataTable MyTable)
{
try
{
if (CreateDatabaseConnection() != null)
{
string strQuery = "SELECT * FROM " + strTableName;
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
OleDbCommandBuilder MyCommandBuilder = new OleDbCommandBuilder(MyAdapter);
MyAdapter.SelectCommand = new OleDbCommand(strQuery, odcConnection);
MyAdapter.UpdateCommand = MyCommandBuilder.GetUpdateCommand();
MyConn.Open();
MyAdapter.Update(MyTable);
MyConn.Close();
}
}
catch { }
}
If I debug this snippet, all variables are what they should be:
strTableName = the correct name for my table
MyConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyLocation;Persist Security Info=True;JET OLEDB:Database Password=MyPassword;"
MyTable = is the correct table that is also used further on by my application
This process runs through without an error and without using the catch but it does not touch my database, it just doesn't do a thing.
Am I dropping the ball here or just missing the obvious, I have no idea but I browsed many articles and apart for showing the MyAdapter.Update(), there doesn't seem to be much more to it.
Any help is welcome.
Thanks,
Kevin
Does your backup database have to be in access? because if you used SQL Compact Edition it'd be much easier to copy between the two?
Yes, it would either mean attaching it with your installer or just ensuring that all client machines have it pre-installed, it is free however.
if this is an issue then all you need to do (I think, not done it myself)
would be to go to your installer projects properties, click prerequisites and then tick SQL compact so that it will be installed before your application can be used, iv done this before with other frameworks and it just pops up a box with the install shield asking whether they want to download the necessary software and its just one click then it should be done for them.
Do you need a hand on using the compact database also?
One negative by the way is it does lack some higher end features but shouldn't affect average database work
EDIT
if you will be using sql CE you can easily make the databse in VS by clicking data and new data source then following the steps making sure to put sql CE when asked
if it works, you'll end up with an .sdf database
I provided a code snippet that fixed the issue on my related question here: Export SQL DataBase to WinForm DataSet and then to MDB Database using DataSet
I have created a desktop application with SQL Server 2008 as backend. I want to use this database from my application that is installed on a number of machines.
What are the requirements for that application to connect to the centralized database.?
It is pretty simple, You want the architecture as Client-Server model were the server has the database .Hence you need to have MS SQLserver 2005 or higher versions and create database connect it to sqlserver. Grant permission for the clients to access the database.
From visual studio side:
Add the above created .mdf(database file) as the new data source.
Data-->Add new Data Source , and follow the steps in the wizard[p.s the type of connection has to be sql sever type ]
while doing this a connection string will be created by VS. Use tht connection string to access from the client side.
This link would be useful : http://msdn.microsoft.com/en-us/library/sxds9ett(v=vs.80).aspx
To keep the connection string in its resources, ofcourse.
Resources are:
Doubleclick on project's Properties (at solution explorer).
Then Settings tab.
If there is no default setting file, create it by clicking the long link label.
Add a setting like "ConnectionString" with the value like "Data Source = ..." whatever.
Then you can run your sql scripts like:
SqlConnection conn =
new SqlConnection(Properties.Settings.Default.ConnectionString);
And go on.
I am developing window phone 7 application. I am new to the Window Phone 7 application development. I want to use the SQL server compact edition database in my application for database connectivity. So in my application I have created the database by right clicking the 'Data Connection' & Choosing the 'Add Connection' in Server Explorer. After that I have created the database by using the Create button in the opened window.Then I have tested my connection. It was successful. I have added that created database file in my application by right clicking on the Project Name & choosing the add existing item. The database file was added as the 'ExpenseManagerDB.sdf' I have created the tables for this database by using the Server Explorer. Now I want to programmatically do the database connectivity for my application. So I am using the following code
namespace ExpenseMgrMobAppl.Category
{
public partial class Category : PhoneApplicationPage
{
private void Submitbutton_Click(object sender, RoutedEventArgs e)
{
string conSTR = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\ExpenseManagerDB.sdf;Persist Security Info=False";
SqlCeConnection connection = new SqlCeConnection(conSTR);
SqlCeCommand cmd = new SqlCeCommand("select category_name form category where category_id=1", connection);
connection.Open();
textBlock1.Text = cmd.ExecuteScalar.ToString();
connection.Close();
}
}
}
But I am not finding any Namespace/Assembly for the SqlCeConnection class. I have also tried to add reference to the dll 'System.Data.SqlServerCE.dll' in my application. But the reference could not be added. What should I need do for database connectivity ? What I need to do to use the SqlCeConnection class in my application ? I am looking for thing from which I can use the SqlCeConnection class in my application ? Can you please provide me any solution or link through which I can resolve the above issue ? If I am doing anything wrong in above case then please guide me.
SQL CE is not available in this release of the tools.
The alternatives are storage behind a web service, 3rd party db sources like Sterling or local storage in files using for example XML and LINQ.
As Mick N says there are some 3rd party databases available for the phone. Have a look at
Perst (Commercial, but I believe free for non-commercial use)
Sterling
Windows Phone 7 Database
However my advice would be to think carefully about whether you really need a full relational database in your app on the phone. If you are just using it to store and retrieve data, binary serialized files are extremely efficient and lightweight.
Remember the phone is a very resource constrained environment. Whereas on the desktop we would immediately turn to a database for most data storage requirements because it makes our life easier. On the phone we need to be more careful and optimize for the environment - even if that makes our lives as programmers a little harder. A full database shouldn't necessarily be the first option when thinking about storing data.
That said if you have a data requirement that you feel warrants a full relational database then you should absolutely use one of the aforementioned DBs.