【发布时间】:2017-07-19 01:24:03
【问题描述】:
我正在构建一个基于库存的应用程序,该应用程序可以直接从任何 PC 运行而无需任何安装,因此我使用的是 SQL CE。在开始时,我正在检查数据库是否存在。如果不是,我将创建新数据库:
try
{
string conString = "Data Source='ITM.sdf';LCID=1033;Password=ABCDEF; Encrypt = TRUE;";
SqlCeEngine engine = new SqlCeEngine(conString);
engine.CreateDatabase();
return true;
}
catch (Exception e)
{
//MessageBox.Show("Database Already Present");
}
数据库已正确创建,我也可以访问数据库来创建表。我面临的问题是 - 我正在使用代码单击按钮以 Windows 形式插入和更新记录:
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
String Name = NameTxt.Text.ToString();
String Phone = PhoneTxt.Text.ToString();
double balance = Double.Parse(BalanceTxt.Text.ToString());
String City = CityTxt.Text.ToString();
string sqlquery = "INSERT INTO Customers (Name,Phone,Balance,City)" + "Values(@name,@phone, @bal, @city)";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("@name", Name);
cmd.Parameters.AddWithValue("@phone", Phone);
cmd.Parameters.AddWithValue("@bal", balance);
cmd.Parameters.AddWithValue("@city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Inserted");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
connection.Close();
}
更新码是
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
int idtoedit = select_id_edit;
String Name = NameEditTxt.Text.ToString();
String Phone = metroTextBox1.Text.ToString();
String City = CityEditTxt.Text.ToString();
string sqlquery = "Update Customers Set Name = @name, Phone = @phone,City = @city where Id = @id";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("@name", Name);
cmd.Parameters.AddWithValue("@phone", Phone);
cmd.Parameters.AddWithValue("@id", idtoedit);
cmd.Parameters.AddWithValue("@city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Updated");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
loadIntoGrid();
connection.Close();
}
每当我执行插入和更新记录的代码时 - 记录都会反映在由数据库表中的适配器填充的数据网格中。但是一旦我重新启动应用程序,值就不会出现在数据库中。百万分之一的值反映在数据库中。我无法理解这个问题背后的原因。
我参考了这些文章:
C# - ExecuteNonQuery() isn't working with SQL Server CE
Insert, Update, Delete are not applied on SQL Server CE database file for Windows Mobile
但由于我以编程方式创建数据库 - 它被直接创建到 bin/debug 目录,我无法在 Visual Studio 的解决方案资源管理器中看到它以更改复制选项
【问题讨论】:
-
只是澄清一下,当
if (x > 0)? 时更新和插入查询同时运行 -
No.. 它们是分开运行的
标签: c# sql .net winforms sql-server-ce