Create setup file include MySQL database inside it - c#

I developed application form using C# and connected this application with a MySQL database like this
string Coonstring = "datasource=localhost;port=3306;username=root;password=***;Charset=utf8";
string cmd = "select name from project.material ;";
MySqlConnection connectionDatabase = new MySqlConnection(Coonstring);
MySqlCommand cmddata = new MySqlCommand(cmd, connectionDatabase);
MySqlDataReader myreader;
When I try to build this app. and create setup file and get this setup file to another laptop error messagbox appear tell me missing MySQL host.
So what should I do ?

Add an application configuration file. MSDN Link
Add an entry for a connection string - this can now be changed when deployed. MSDN Link
Change your code to use it (as shown below).
Set the connection string appropriately on the deployed system in the *.exe.config file.
string Coonstring = ConfigurationManager
.ConnectionStrings["KeyValueYouSupplied"]
.ConnectionString;

Related

Cannot add sqlite db file to Word adding deployment

I developed C# Word add-in which populates some data from database file. It is working fine while I am running through Visual studio running. But if I publish it cannot connect to database.
Here is how I get data from database:
SQLiteConnection con = new SQLiteConnection(ThisAddIn.connectionString);
con.Open();
var command = con.CreateCommand();
command.CommandText =
#"
SELECT *
FROM JK
WHERE article_number = $article_number
";
command.Parameters.AddWithValue("$article_number", textFromDoc);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var title = reader.GetString(2);
var article = reader.GetString(3);
ResultForm resultForm = new ResultForm();
resultForm.setArticle(title, article);
resultForm.ShowDialog();
}
}
public static string connectionString = #"Data Source=E:\projects\c#\TBPWordAddin\WordAddIn1\codexes.db";
Am I doing something wrong or do I need to include file in another way? Any help will be appreciated.
Also I tried publishing using Visual studio installer and it connected to database but the add in didnot lounched on other computers.
The connection string contains an absolute path which can be changed after publishing an application. I'd suggest using a relative path instead - in that case you will be able to find the Db easily. You may check out the following threads for more information on such kind of issues:
Connection string with relative path to the database file
How to give relative path of connection string or data source in windows form application
But if I publish it cannot connect to database.
Make sure the Db path (see the connection string) corresponds to the hardcoded value in the application used.

Unable to load database from local server location in C# Connection String (windows application)

I'm trying to do application to access the database from local file server, but the connection string does not recognize the server location. This is a windows form application, using sqlite. Kindly help me on this one.
File server location will be like this:
\\fileserver\Testdb\maindb.db
Code used:
string server_database_path = #"\\fileserver\Testdb\maindb.db";
string connection_data = "Data Source=" + server_database_path ;
using (var conn = new SQLiteConnection(connection_data))
{
conn.Open();
SQLiteCommand insert_Rec = new SQLiteCommand(query_text, conn);
insert_Rec.ExecuteNonQuery();
conn.Close();
}
Error:
Unable to open database file
I may be wrong but I dont think that directly specifying the .db is correct. When using a normal SQL Server I would specify the instance (or just the server hosting it if it was the default instance).
So, your connection string should look something like
string connectionString = "Data Source=192.168.0.1; User ID=administrator; Password=YOURPASSWORD"
or if you are connecting the machine you are on it should be
string connectionString = "Data Source=127.0.0.1; User ID=administrator; Password=YOURPASSWORD"
You could substitute the 127.0.0.1 for \\localhost
I was confused in doing this, but by changing the slash "\" to "/" it really worked.
When i changed the slash in the path string it started to work fine and everything goes well.
Example: #"//fileserver/Testdb/maindb.db"

How to save DataSet after adding data?

Yes, I know that this questions has been asked at least 5-10 times in here, but I can't for the life of me get any of the methods to save the data.
The idea is to create a new row in table Companies in column Name (there is only one column) with value "asdf"`.
I've tried combinations of the following:
DatabaseDataSetTableAdapters.CompaniesTableAdapter adapter = new DatabaseDataSetTableAdapters.CompaniesTableAdapter();
DatabaseDataSet ds = new DatabaseDataSet();
adapter.Insert("asdf");
adapter.Fill(ds.Companies);
adapter.Update(ds.Companies);
ds.AcceptChanges();
ds.Companies.AddCompaniesRow("asdf");
ds.Companies.AcceptChanges();
ds.Companies.AddCompaniesRow("asdf");
ds.Companies.Rows[0]["Name"] = "asdf";
adapter.Update(ds.Companies);
I'm using C# WPF .NET 4.5.1
It does add the data, but it doesn't save it when I exit the program - I know that it adds data, because if I call this method twice it crashes, because the value is no longer unique.
Here is the DatabaseDataSetTableAdapters:
http://pastebin.com/gNsaRFD5
This did not work either:
SqlConnection myConnection = new SqlConnection(global::AliBabaMailer.Properties.Settings.Default.DatabaseConnectionString);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("INSERT INTO Companies (Name) " +
"Values ('string')", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
Ok so your problem is the Connection String:
Properties.Settings.Default.DatabaseConnectionString
This connection string is of the form:
“Data Source=ServerName;AttachDbFilename=|DataDirectory|\DataBaseName;Integrated Security=True”
The |DataDirectory| is usually here:
C:\Users\UserName\AppData
When you save the data it is being saved to a database file at `|DataDirectory| location but when you try to view the data using Server Explorer you are trying to view from a database file which is in your project's folder, that is why If you try to save and then view the data on run time it will work fine because then you will be querying the same database you are storing your data into.
|DataDirectory|:
|DataDirectory| (enclosed in pipe symbols) is a substitution string that indicates the path to the database. It eliminates the need to hard-code the full path which leads to several problems as the full path to the database could be serialized in different places. |DataDirectory| also makes it easy to share a project and also to deploy an application.
For example, instead of having the following connection string:
"Data Source= c:\program files\MyApp\Mydb.sdf"
Using DataDirectory, you can have the following connection string:
“Data Source = |DataDirectory|\Mydb.sdf”
To set the DataDirectory property, call the AppDomain.SetData method. If you do not set the DataDirectory property, the following default rules will be applied to access the database folder:
For applications that are put in a folder on the user's computer, the database folder uses the application folder.
For applications that are running under ClickOnce, the database folder uses the specific data folder that is created.
Link
Coding Advice:
Try to dispose your Command and Connection Objects like this:
using(SqlConnection myConnection = new SqlConnection(global::AliBabaMailer.Properties.Settings.Default.DatabaseConnectionString))
using(SqlCommand myCommand = new SqlCommand("INSERT INTO Companies (Name) " + "Values ('string')", myConnection))
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}

how to set a path to the local directory in c# for .mdf database in Service.cs file

Do you know how to set a path to the local directory in c# when trying to set a path for a datbase in the service.cs file? (I am developing in VS2010)
I have developed a winforms program that uses a .mdf (SQL Server) database. The program communicates to the database through a SQL Server connection string.
I have hard coded the path of the db at the mo but would like to know how to point to the current directory.
I have seen online
AttachDbFilename =|DataDirectory|\Database.mdf
But it doesn't seem to work for me as the connection will not open.
Also I have tried using Environment.CurrentDirectory however that with CurrentDirectory is weirdly not in the namespace.
If the file is in the same assembly folder you can use this
string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["myCS"].ConnectionString = config.ConnectionStrings.ConnectionStrings["myCS"].ConnectionString.Replace("#folder#",folder);
config.Save(ConfigurationSaveMode.Full, true);
Go to solution Explorer >> right click the project>> click properties>> go to setting tab>>Make name: MyConnectionString Type:(connection string) Scoper: Application
and select the DB(Db should be kept in your |DataDirectory| along with your dblog)>> select that DB. >> save it.
Then use this code for connection
SqlCeConnection cnn = new SqlCeConnection(Properties.Settings.Default.MyConnectionString);
You have to give the namespace: using System.Data.SqlServerCe;
hope this will solve.
Accept if this works and close the question
there is a way to get the .mdf and .ldf of a databese, through the code that have worked for me, to do that, open a connection to the database using the connection string, prepare SQL command, with the query
select physical_name from sys.database_files where type = 0
then execute the command, and by the way, type = 0, is for mdf, and type = 1 is for ldf, you can also use this query directly in the SSMS
this is the sample code, keep in mind that you need to get the connection string
string _mdfCommand = "select physical_name from sys.database_files where type = 0";
string _ldfCommand = "select physical_name from sys.database_files where type = 1";
SqlCommand GetSQLData = new SqlCommand();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
GetSQLData.CommandText = _mdfCommand;
GetSQLData.Connection = connection;
string mdf_Path= (string)GetSQLData.ExecuteScalar();
GetSQLData.CommandText = _ldfCommand;
GetSQLData.Connection = connection;
string ldf_Path= (string)GetSQLData.ExecuteScalar();
connection.Close();

Can't create a sql connection due to the fact that it won't rcognize the data source keyword

Hello I'm trying to run a simple sql command on a DB from MS VS C# 2010 and I have encountered a error I have never seen before the relevant code is:
SqlConnection comCon = new SqlConnection(#"Data Source=C:\\Users\\George\\Desktop\\programming\\C#workspace\\Projects\\Examen\\Examen\\Companie.mdf;Initial Catalog=Proiect;Integrated Security=True"); 
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Proiect SET Buget = Buget + 500 WHERE (Buget > 0)";
cmd.Connection = comCon;                                                      
comCon.Open();
Console.WriteLine(cmd.ExecuteNonQuery().ToString());
comCon.Close();
And the error is Keyword not supported: 'data source'
The main problem is that I'm not used to creating these sqlconnections by hand so please tell me if I'm missing something.
You are using the wrong structure. To attach a database file, you need to use the following structure:
SqlConnection sqlConnection =
"Server=DatabaseServerName;AttachDbFilename=d:\Database\Database.mdf;
Database=DatabaseName; Trusted_Connection=Yes";
You need to have the right permissions on both the target file and database server to attach the databse and establish the connection.
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
If it's not an ASP.NET application don't use the DataDirectory syntax and just use the full c:... path.

Categories

Resources