首页 > 解决方案 > 在客户端 PC 上生成 SQL 数据库

问题描述

我有一个使用 SQL Server 的应用程序,并且我正在处理一个应该从脚本在客户端计算机上生成数据库的设置。作为安装的先决条件,我选择了 SQL Server Express 2012 和 .Net Framework。我的问题是,SQL Server Express 2012 是否足以让在客户端机器上访问数据库成为可能?此外,我的用于从脚本生成数据库的代码是否会在另一台 PC 上运行,特别是“Data Source=.\BeneSQL”让我担心,因为这对我的 PC 来说是“唯一的”,还是脚本也会生成该部分?

private void Form1_Load(object sender, EventArgs e)
        {
            if (!CheckDatabaseExist())
            {
                GenerateDatabase();
            }
        }

        private bool CheckDatabaseExist()
        {
            SqlConnection sqlConnection = new SqlConnection(@"Data Source=.\BeneSQL;Initial Catalog=TryingDB;Integrated Security=True");
            try
            {
                sqlConnection.Open();       

                return true;

            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }
        }

        private void GenerateDatabase()
        {
            List<string> cmds = new List<string>();
            if (File.Exists(Application.StartupPath + "\\Skript.sql"))
            {
                TextReader tr = new StreamReader(Application.StartupPath + "\\Skript.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();
                command.Connection = new SqlConnection(@"Data Source=.\BeneSQL;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();
                }
            }
        }

标签: c#sql-server

解决方案


由于您怀疑的原因,我看不到它的工作原理。

尝试

                command.Connection = new SqlConnection(@"Data Source=localhost;Initial Catalog=MASTER;Integrated Security=True");

推荐阅读