. Net installation package automatically installs Mysql database

Source: Internet
Author: User
Tags custom name

When creating the. Net installation package, how can I package and install the database if the project is useful to the database? There are already many examples of Automatic Installation of SQL Server databases on the Internet, but there are not many examples of Automatic Installation of mysql. This article describes how to automatically install the Mysql database in the. Net installation package.

The final result we need to achieve is that when deploying. Net desktop applications, we can automatically install the application and the MySql database that comes with it with one click and initialize the database.

The implementation steps are as follows:

 

Mysql itself is open-source. After the mysql database is installed, a Windows service is installed in the system (compared with the Windows system)

Can download a mysql version from the Internet, for example, I am using Mysql5.5,: http://dev.mysql.com/downloads/mysql/5.5.html

Download the installation package. After the installation is completed according to the normal installation process, directly copy the installed directory for subsequent installation projects.

The general mysql directory is as follows:

 

After copying a copy of the Mysql directory, You need to modify the mysql settings as required by the project, such as setting cache size, storage type, and other parameters.

Special settings are required:

PortSpecial settings are required. Generally, the default port is port 3306. To prevent conflicts, change the port to port 3307.

[Mysqld]

# The TCP/IP Port the MySQL Server will listen on port = 3307

BasedirYou need to modify the Directory, which is the physical location of the MySql folder. dynamic configuration is required here. We will replace it with a custom placeholder, which will be modified later in the program.

# Path to installation directory. All paths are usually resolved relative to this.
Basedir = "% BaseDir %/MySQL Server 5.5 /"

DatadirYou need to modify the directory. This directory is the path for storing Mysql Data. It also needs to be dynamically configured. It is temporarily replaced by a placeholder and later modified by a program.

# Path to the database root
Datadir = "% BaseDir %/MySQL Server 5.5/data /"

 

For testing, I have created the following three projects:

The setup1 project is the. Net installation project.

MySqlAutoInstall is a simulated desktop program that uses the mysql database.

The InserterDb Project is a DLL class library project, which is used to install the mysql database. We will call this library in the setup1 project to implement automatic installation of the mysq database.

 

Right-click the Setup1 project, select "View"> "File System", and drag the clean Mysql database folder prepared in step 1 to the "Application folder.

Create another "your program" folder (with a custom name) and put your desktop program below. In this example, the MySqlAutoInstall project is used.

 

Create a class library project for InserterDb and add an "Installer class" Installer1.cs

The Code is as follows:

Using System; using System. collections; using System. collections. generic; using System. componentModel; using System. configuration. install; using System. linq; using MySql. data. mySqlClient; using System. IO; using System. threading; namespace inserterDb {[RunInstaller (true)] public partial class Installer1: System. configuration. install. installer {public Installer1 () {InitializeComponent ();} public override Void Install (IDictionary stateSaver) {base. Install (stateSaver); InsertMySql (); CreatDataBase (); Log ("installation successful! ");} // Install mysql protected void InsertMySql () {string physicalRoot = this. context. parameters ["targetdir"]; // installation physical path C: \ program \ microp string appPath = physicalRoot + "\ MySQL Server 5.5 \"; // 1. modify my. ini configuration to prevent mysql installation on the local machine, modify my. the port in ini is 3307 string iniFile = File. readAllText (appPath + "my. ini "); iniFile = iniFile. replace ("% BaseDir %", physicalRoot. replace ("\", "/"); // % BaseDir % is my. file. wr IteAllText (appPath + "my. ini", iniFile); Log ("create win service ...... "); // 2. create win service string info1 = CommandHelper. execute (appPath + "bin \ mysqld.exe", "install MySQL2 -- defaults-file = \" "+ appPath +" my. ini \ "", 0); Log (info1); Thread. sleep (3000); Log ("start service with net start"); // 3. start the service string info2 = CommandHelper. execute ("net start MySQL2", 0); Log (info2); Log ("the service has been started! "); Thread. sleep (5000); MySqlConnection con = new MySqlConnection ("Data Source = 'localhost'; Port = '000000'; Database =''; User Id = 'root '; password = '';"); try {con. open (); con. close (); Log ("connection successful! ");} Catch (Exception ex) {Log (" connection failed! "+ Ex. message) ;}} // create a database and initialize the table protected void CreatDataBase () {string physicalRoot = this. context. parameters ["targetdir"]; // installation physical path C: \ program \ microp string mysqlcon = "Data Source = 'localhost'; Port = '123 '; database = '{0}'; User Id = 'root'; Password = '';"; MySqlConnection conn = new MySqlConnection (string. format (mysqlcon, ""); FileInfo file = new FileInfo (physicalRoot + "\ DBInit \ yourDB. SQL "); // fi Lename is the path of the SQL script file. String SQL = file. openText (). readToEnd (); try {MySqlScript script = new MySqlScript (conn); script. query = SQL; int count = script. execute (); Log ("database Initialization is complete! "); MySqlConnection con2 = new MySqlConnection (string. format (mysqlcon, "yourDB"); con2.Open (); MySqlCommand dbcom = new MySqlCommand ("select count (*) from t_image", con2); dbcom. executeScalar (); con2.Close (); Log ("database creation OK! "); // Modify the database link address in config. xml} catch (Exception ex2) {Log (" database creation failed! "+ Ex2.Message) ;}}// write the Log protected void Log (string line) {string physicalRoot = this. context. parameters ["targetdir"]; // installation physical path C: \ program \ microp string filePath = physicalRoot + "Install_log.txt"; if (File. exists (filePath) {File. appendAllLines (filePath, new string [] {DateTime. now. toString ("[yyyy-MM-dd HH: mm: ss]") + line});} else {File. writeAllLines (filePath, new string [] {DateTime. now. toString ("[yyyy-MM-dd HH: mm: ss]") + line });}}}}

 

This override void Install method starts database installation immediately after the program is installed.

To install a MySql database using code, follow these steps:

1) modify the configuration of my. ini to prevent mysql installation on the local machine. Specifically, set the port number in my. ini to 3307.

The path in my. ini should be set to the installation directory of the installer. This directory is customized by the user. You can pass parameters by setting the customActionData attribute of Setup. For details, see the following section.

2. Use the “mysqld.exe-install command to install the mysql database service.

3) Use net start to start the Mysql Service

4) Verify the database installation result

5) execute the initialization script to initialize the database.

 

Right-click the "setup1" project, select "View"-"Custom operations", right-click the "Install" folder, select "add custom operations", and select the class library project of InserterDb created in step 1.

Set the attributes of the newly added custom operation./mactiondata is/targetdir = "[TARGETDIR] \"

The targetdir here is a custom parameter name to obtain the installation path of the selected program. It is used to modify the % BaseDir % parameter in the Mysql configuration file.

 

Download the test Source code: Source

Note: Because the mysql file is too large, only the directory name is left in the directory. copy the file yourself.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.