简体   繁体   中英

How to connect database with C# executable file?

I am writing code for a small company that is all about purchase and sell. I wrote C# code with using external database (SQL Server 2014), now it's time to make the exe file of that code.

I tried my best but it doesn't work.

How can I connect SQL Server 2014 database files with my application so that when someone installs it on his computer he also got SQL Server connected with that application?

Ideally you'd have a SQL server set up somewhere. If not you'll have to install sql server. In your app it's just a matter of setting up the connection string and running sql commands against it.

string connectionString = "Data Source=server //rest of connection string"

Then in c# you can do

using (SqlConnection con = new SqlConnection(connectionString))
{
    using (SqlCommand command = new SqlCommand("SELECT TOP 100 * FROM SomeTable", con))
    using (SqlDataReader reader = command.ExecuteReader())
    {
    while (reader.Read())
    {
        Console.WriteLine("{0} {1} {2}",
        reader.GetString(0), reader.GetString(1), reader.GetString(2));
    }
    }

 }

GetString can be changed to GetInt or whatever the datatable will be. This should be enough information to get you started. If you know the structure of the database its simple to put the results into your classes for the application.

Hi actually we deploy code as setup file (.msi), you can create setup project using Wix or install-shield ( maybe other too,but these two are most popular and widely used)

You can do database deployment in two ways

1.) you can provide SQL script for generating SQL server and give instruction for generating Database from Script. It is simple and easy to do.

2.) Other way is provide option to create database from setup. It need some work, but it is more good way.

Now come to your question, you can provide some UI in setup that take input from user and connect to appropriate DB. Or create a UI for Updating configurations, and save configuration (connection string ) in some file ( ex: .ini or .config file).

Below are the some URL for creating Setup and connecting to Db using Wix:

WIXDataBase

installing-databases-using-wix

Creating-an-installer-using-Wix

using-wix-to-install-sql-databases-and-execute-sql-scripts

WiX Samples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM