0
对于我正在制作的程序,我想在表格中添加countrycode,城市的邮政编码和城市的名称。如果此信息已在表格中,则不需要发生任何事情。插入数据以访问C#数据库#
但是,新记录不会插入我的表中。
例如:只有BE,'3580','Beringen'在我的桌子上。我开始我的程序。 首先我插入已经在我的表中的值,但没有任何事情发生。
第二我尝试添加一个新值(例如:('BE''3500','Hasselt'))。我得到的消息框:“数据添加成功!”。
之后,我尝试添加与之前相同的值('BE''3500','Hasselt')。我的程序什么都不做。
但是当我打开Access时,请看一下表格。没有新的数据被添加。
我做错了什么?
connection.ConnectionString = @"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = DeJongDatabase.mdb; Persist Security Info = True";
这是我的代码
static class Zipcodes
{
public static void checkAndSavePostCode(String country, String zipcode, string city)
{
Globals.connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = Globals.connection;
command.CommandText = string.Format("SELECT * FROM Zipcodes WHERE CountryCode = @countryCode AND City= @city AND Zipcode= @zipcode");
command.Parameters.AddWithValue("@countyCode", country);
command.Parameters.AddWithValue("@city", city);
command.Parameters.AddWithValue("@zipcode", zipcode);
OleDbDataReader postcodeReader = command.ExecuteReader();
bool exists = false;
while (postcodeReader.Read())
{
exists = true;
}
postcodeReader.Close();
command.Dispose();
Globals.connection.Close();
OleDbCommand writeCommand = new OleDbCommand();
writeCommand.Connection = Globals.connection;
try
{
Globals.connection.Open();
if (!exists)
{
if (Globals.connection.State == System.Data.ConnectionState.Open)
{
/*writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(@countryCode, @zipcode, @city)";
writeCommand.Parameters.AddWithValue("@countyCode", country);
writeCommand.Parameters.AddWithValue("@city", city);
writeCommand.Parameters.AddWithValue("@zipcode", zipcode); */
writeCommand.CommandText = "INSERT INTO Zipcodes(CountryCode, ZipCode, City) VALUES(?, ?, ?)";
writeCommand.Parameters.Add(new OleDbParameter("@countryCode", OleDbType.VarChar)).Value = country;
writeCommand.Parameters.Add(new OleDbParameter("@zipcode", OleDbType.VarChar)).Value = zipcode;
writeCommand.Parameters.Add(new OleDbParameter("@city", OleDbType.VarChar)).Value = city;
if (writeCommand.ExecuteNonQuery() > 0)
{
MessageBox.Show("Data saved successfuly...!");
}
}
else
{
MessageBox.Show("FAILED");
}
}
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Source);
MessageBox.Show(ex.ToString());
}
finally
{
Globals.connection.Close();
}
这通常意味着您正在查看数据库的副本。 – LarsTech
_“我尝试添加与以前相同的值,我的程序不会执行任何操作”_您期待它做什么?如果'exists = true',那么没有代码要执行.. – stuartd
检查数据库的位置,你想要更新的位置应该在bin \ Debug文件夹中(你可能在解决方案文件夹中检查mdb文件) – Nino