How Create DataBase in SqlServer2008 Express With Code Lines

痴心易碎 提交于 2019-12-24 20:11:37

问题


I Work on C# Project (WinForm)

I Install Sql Server 2008 Express On Client PC.

in Start Of My Program Must Create a Database. So I Use This Code For Create a Database:

string sqlCreateDBQuery;

            SqlConnection tmpConn = new SqlConnection(@"SERVER =.\SQLEXPRESS; Trusted_Connection = yes;DATABASE = master;");

            sqlCreateDBQuery = " CREATE DATABASE "
                               + DatabaseName
                               + " ON PRIMARY "
                               + " (NAME = " + DatabaseName + ", "
                               + " FILENAME = '" + @"C:" + @"\" + DatabaseName + ".mdf" + "', "
                               + " SIZE = 3MB,"
                               + " FILEGROWTH = " + "10%" + ") "
                               + " LOG ON (NAME =" + "MyDatabase_Log" + ", "
                               + " FILENAME = '" + @"C:" + @"\" + DatabaseName + "_log.ldf" + "', "
                               + " SIZE = 1MB, "
                               + " FILEGROWTH = " + "10%" + ") ";
            sqlCreateDBQuery = Coomand;

            SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
            try
            {
                tmpConn.Open();
                MessageBox.Show(sqlCreateDBQuery);
                myCommand.ExecuteNonQuery();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                tmpConn.Close();
            }
            return;

But When My Program Run I See Following Error

What is My Problem?


回答1:


It looks from the error message that you don't have permissions to create your mdf file on the root. Truth be told, you should not have put it there anyway, as that is much too exposed. Put it in your application's folder, or somewhere obscure where it won't be accidentally deleted.

I also think that you should be running this as a install script for the initial setup, rather than in your code. I am a big proponent of keeping sql out of code as much as possible, but to each his own. You say you set up the SQL Server DB, you should use the tools at your disposal to make this easy for you. I had a book from Wrox that served me well, here is the link: http://www.wrox.com/WileyCDA/WroxTitle/Wrox-s-SQL-Server-2005-Express-Edition-Starter-Kit.productCd-0764589237.html -Amazon has it for $2 - http://www.amazon.com/Server-Express-Edition-Starter-Programmer/dp/B006TQYC8U/ref=sr_1_1?ie=UTF8&qid=1342019983&sr=8-1&keywords=Wrox%27s+SQL+Server+2005+Express+Edition+Starter+Kit

Also:

http://msdn.microsoft.com/en-us/library/bb264562(v=sql.90).aspx



来源:https://stackoverflow.com/questions/11435536/how-create-database-in-sqlserver2008-express-with-code-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!