簡體   English   中英

需要幫助寫入SQL Server CE表

[英]Need help writing to a SQL Server CE table

我一直試圖讓下面的代碼寫入我的SQL Server CE數據庫幾個月沒有成功。 我的嘗試捕獲不會捕獲拋出的錯誤,但我的數據不會被寫入。 有沒有人看到我這樣做的方式有什么問題?

conn = new SqlCeConnection("Data Source = LaZSolutions.sdf");
conn.Open();

var id = Guid.NewGuid();

SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO Customers (FirstName, LastName, Address, City, State, Zip, Phone, Mobile, Email, CustomerNum) VALUES(@FirstName, @LastName, @Address, @City, @State, @Zip, @HomePhone, @MobilePhone, @Email, @CustomerNum)";

cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("@FirstName", txtFName.Text);
cmd.Parameters.AddWithValue("@LastName", txtLName.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@HomePhone", txtHPhone.Text);
cmd.Parameters.AddWithValue("@MobilePhone", txtMPhone.Text);
cmd.Parameters.AddWithValue("@City", txtCity.Text);
cmd.Parameters.AddWithValue("@State", txtState.Text);
cmd.Parameters.AddWithValue("@Zip", txtZip.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
cmd.Parameters.AddWithValue("@CustomerNum", id);

cmd.ExecuteNonQuery();

conn1 = new SqlCeConnection("Data Source = LaZSolutions.sdf");
conn1.Open();

SqlCeCommand cmd1 = conn1.CreateCommand();
cmd1.CommandText = "INSERT INTO Orders (OrderNum, OrderDate, Cost, [Open], Comments) VALUES(@OrderNum, @OrderDate, @Cost, @Open, @Comments)";

cmd1.CommandType = CommandType.Text;
cmd1.Connection = conn1;
cmd1.Parameters.AddWithValue("@OrderNum", txtOrderNum.Text);
cmd1.Parameters.AddWithValue("@OrderDate", txtOrderdate.Text);
cmd1.Parameters.AddWithValue("@Cost", lblPrice.Text);
cmd1.Parameters.AddWithValue("@Open", open);
cmd1.Parameters.AddWithValue("@CustomerNum", id);
cmd1.Parameters.AddWithValue("@Comments", txtComments.Text);

cmd1.ExecuteNonQuery();
conn1.Close();
conn.Close();

您的代碼似乎是正確的(盡管您沒有使用using語句封裝您的一次性元素,並且打開時不需要兩次相同的連接)但是,您的SDF文件列在連接字符串中而沒有任何路徑。 這意味着此文件應位於運行程序的同一文件夾中。 調試程序時,可執行文件在BIN \\ DEBUG目錄中運行,如果插入成功,則數據將插入BIN \\ DEBUG目錄中的SDF文件中。

您可以檢查插入是否可以將整數變量分配給ExecuteScalar的返回值。 如果此變量為1,則表示您的代碼已插入記錄。

現在,如果使用Server Manager檢查文件的內容,則需要確保顯示的數據庫與BIN \\ DEBUG中的數據庫相同,而不是通常存在於項目文件夾根目錄中的基本文件。

另一種可能性是文件所在文件夾的寫權限問題,但這會導致異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM