How Create DataBase in SqlServer2008 Express With

2019-09-08 18:56发布

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

enter image description here

What is My Problem?

1条回答
Evening l夕情丶
2楼-- · 2019-09-08 19:04

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

查看更多
登录 后发表回答