我是新來的C#&我試圖以編程方式創建&打開一個SQL Server數據庫。創建並連接到SQL Server數據庫的代碼:它有什麼問題?
我有一個ASP.NET web應用程序,我在頁面加載創建&應該從數據庫中獲取一些數據(如果該數據庫不存在,應創建&默認數據填充)。
PS:請問C#的System.Data.SqlClient
使用MySQL或SQLite或其他?
現在我不確定我的代碼是否正確創建了SQL Server數據庫&如果我正確連接它。
你能告訴我,如果我的代碼是正確的&我該如何改進它?
UPDATE:錯誤是
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"}"
我已表明其中在下面的代碼發生錯誤。
創建SQL Server數據庫:
// When I run this function no file seems to be created in my project directory?
// Although there is a ASPNETDB sql database file in my App_Data folder so this maybe it
public static string DEF_DB_NAME = "mydb.db"; // is this the correct extension?
private bool populateDbDefData()
{
bool res = false;
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");
string str = "CREATE DATABASE "+DEF_DB_NAME+" ON PRIMARY " +
"(NAME = " + DEF_DB_NAME + "_Data, " +
"FILENAME = " + DEF_DB_NAME + ".mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = " + DEF_DB_NAME + "_Log, " +
"FILENAME = " + DEF_DB_NAME + "Log.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open(); // ERROR OCCURS HERE
myCommand.ExecuteNonQuery();
insertDefData(myConn);
}
catch (System.Exception ex)
{
res = false;
}
finally
{
if (myConn.State == ConnectionState.Open)
myConn.Close();
res = true;
}
return res;
}
這裏是我的SQL Server數據庫的代碼連接:我敢肯定它連接失敗 - 如果我嘗試使用變量康涅狄格州,它說的連接沒開。這可能意味着,我要麼無法接通或甚至未能建立在第一名的DB:
private bool connect()
{
bool res = false;
try
{
conn = new SqlConnection("user id=username;" +
"password=password;" +
"Server=localhost;" +
"Trusted_Connection=yes;" +
"database="+DEF_DB_NAME+"; " +
"connection timeout=30");
conn.Open();
return true;
}
catch (Exception e)
{
}
return false;
}
想必你已經收到了一些錯誤信息? – 2012-02-17 00:29:35
你絕對不應該在頁面加載時創建數據庫。如果兩個人同時碰到網頁怎麼辦? – 2012-02-17 00:30:34
@KirkWoll是的,如果我嘗試使用變量conn,它說連接沒有打開。這可能意味着我要麼連接失敗,要麼失敗,甚至無法創建數據庫第一名 – 2012-02-17 00:31:39