You are on page 1of 5

1.

Nguồn số 1
Code : 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace DeployWithDataBase
{
    public partial class Form1 : Form
  {

        public Form1()
    {
            InitializeComponent();
    }

        private void Form1_Load(object sender, EventArgs e)


    {
            //Here We are checking whether database exist or not it returns bool value if not then
it generate the database
            if (!CheckDatabaseExist())
      {
                GenerateDatabase();
      }
    }

        private bool CheckDatabaseExist()


    {
            //Sql Connection for User Defined Database
            SqlConnection Connection = new SqlConnection(@"Data Source=.\sqlexpress;Initial
Catalog=Collage;Integrated Security=True");
            try
      {
                Connection.Open();
                return true;
      }
            catch
      {
                return false;
      }
    }

        private void GenerateDatabase()


    {
            List<string> cmds = new List<string>();
            //Here we are reading our script file from the installed application folder
            if (File.Exists(Application.StartupPath + "\\Script.sql"))
      {
                TextReader tr = new StreamReader(Application.StartupPath + "\\Script.sql");
                string line = "";
                string cmd = "";
                while ((line = tr.ReadLine()) != null)
        {
                    if (line.Trim().ToUpper() == "GO")
          {
                        cmds.Add(cmd);
                        cmd = "";
          }
                    else
          {
                        cmd += line + "\r\n";
          }
        }
                if (cmd.Length > 0)
        {
                    cmds.Add(cmd);
                    cmd = "";
        }
                tr.Close();
      }
            if (cmds.Count > 0)
      {
                SqlCommand command = new SqlCommand();
                //Sql Connection for Master Database
                //This sql connection for master database it is used to generate database
                command.Connection = new SqlConnection(@"Data Source=.\sqlexpress;Initial
Catalog=MASTER;Integrated Security=True");
                command.CommandType = System.Data.CommandType.Text;
                command.Connection.Open();
                for (int i = 0; i < cmds.Count; i++)
        {
                    command.CommandText = cmds[i];
                    command.ExecuteNonQuery();
        }
      }
    }
  }
}

2. Nguồn số 2
Đóng gói phần mềm + Database 
Sau khi viết xong phần mềm, để đóng gói thành file cài đặt gvà chạy được trên máy không cài
SQL Server cần làm như sau:

1. Right click vào Solution của bạn > Add > New Project...

2. Trong cửa sổ New Project > Orther Project Types > Setup Project > Đặt tên > chỉ đường dẫn
lưu file setup của bạn > OK.

3. Sau khi tạo xong Setup Project trong Solution Explorer của bạn sẽ có xuất hiện Project bạn
vừa tạo. Right Click vào Project đó > Add > Project Output.
4. Trong cửa sổ Project Output chọn Primary output > OK.

5. Right click vào Project Setup vừa tạo > Properties > Prerequisites > Check vào .NET
Framework, SQLEXPRESS 2005 > Check vào radio button ở giữa (download .... my
applications) > OK.

6. Để tạo shortcut ngoài desktop bạn vào Application Folder > Right click vào file Primary output
... > Chọn Creat shortcut .... > Đổi tên shortcut theo ý bạn.
- Bạn tìm một file *.ico rồi add vào application folder bằng cách right lick vào folder application
folder > Add > Files...> chỉ đường dẫn tới file icon của bạn.
- Sau đó right click vào shortcut vừa tạo chọn properties > trong properties tìm đến dòng icon >
Browser > Application folder > chọn file icon vừa add > OK.
- Kéo shortcut vừa tạo thả vào folder user's desktop

7. Add thêm file SQL của bạn gồm 2 file là *.mdf và *.ldf vào application folder.

8. Tạo câu lệnh attach file *.mdf của bạn vào SQLEXPRESS 2005:
datasource=.\SQLEXPRESS;attachdbfilename=c:\Progra m Files\tên project setup của bạn\tên
file mdf;Integrated Security=true;user instanced=true;connect timeout=30;
- vd: datasource=.\SQLEXPRESS;attachdbfilename=c:\Progra m Files\Setup1\
QLST.mdf;Integrated Security=true;user instanced=true;connect timeout=30;
đường dẫn này chỉ hoạt động được khi bạn cài chương trình của bạn vào máy cài win xp.
nếu là win vista hay win 7 bạn phải thêm một chút là:
- vd: Server=.\SQLExpress;AttachDbFilename=|DataDirector y|mydbfile.mdf;
Database=dbname;Trusted_Connection=Yes;

9. Right click vào project output > Build...

10. Cài đặt và chạy thôi:


Trong quá trình cài đặt chương trình sẽ tự kiểm tra xem máy đã có .NET Framework và
SQLEXPRESS 2005 chưa. nếu chưa có sẽ tiến hành cài đặt, sau đó mới cài chương trình của
bạn viết, nếu có rồi thì chỉ cài chương trình của bạn viết thôi.

-Nếu database của bạn là access thì càng đơn giản hơn:
chỉ cần add file access đó vào application folder là xong.

Chúc bạn thành công !


3. Nguồn số 3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using HospitalManager.Business_Logic_Layer;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Collections.Specialized;
 
namespace HospitalManager
{
    static class Program
    {
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
 
            try
            {
                //check database exists
                String DatabaseName = "Hospital";
 
                Server SqlServer = new Server(@".\SQLEXPRESS");
                ServerConnection SqlServerConnection = SqlServer.ConnectionContext;
 
                SqlServerConnection.LoginSecure = true;
                SqlServerConnection.DatabaseName = "master";
 
                if (SqlServer.Databases[DatabaseName] == null)
                {
                    Database NewDatabase = new Database(SqlServer, DatabaseName);
 
                    FileGroup
DatabaseFileGroup = new FileGroup(NewDatabase, "PRIMARY");
                    NewDatabase.FileGroups.Add(DatabaseFileGroup);
 
                    DataFile DatabaseDataFile = new DataFile(DatabaseFileGroup,
DatabaseName);
                    DatabaseFileGroup.Files.Add(DatabaseDataFile);
 
                   
DatabaseDataFile.FileName = Application.StartupPath + "\\" + DatabaseName + ".mdf";
 
                    LogFile DatabaseLogFile = new LogFile(NewDatabase,
DatabaseName + "_log");
                    NewDatabase.LogFiles.Add(DatabaseLogFile);
 
                   
DatabaseLogFile.FileName = Application.StartupPath + "\\" + DatabaseName + "_log.ld
f";
 
                    StringCollection
DatabaseFilesCollection = new StringCollection();
 
                    DatabaseFilesCollection.Add(DatabaseDataFile.FileName);
                    DatabaseFilesCollection.Add(DatabaseLogFile.FileName);
 
                    SqlServer.AttachDatabase(DatabaseName,
DatabaseFilesCollection);
                }
            }
            catch
            {
                MessageBox.Show("Co loi khi thiet lap co so du lieu", "Hospital
Manager");
            }
 
            Application.Run(new Presentation_Layer.frmHospitalManager());
        }
    }
}

sướng quá, mình làm được rồi! add thêm 2 thư viện using Microsoft.SqlServer.Smo; và
using Microsoft.SqlServer.ConnectrionInfo vào References là okie rồi!

You might also like