简体   繁体   中英

c# how to properly write into a .dbf (foxpro)

I am trying to insert new data into an old .dbf database created with foxpro. The database has a lot of columns and I dont need to fill every single one.

The connection itself works. But now im getting the exception "Field XY does not allow null values" for every single one I'm not adding in my insert statement. But the database is configured to allow null values.

I am using the following code:

         OleDbConnection dbfcon = new OleDbConnection("Provider=VFPOLEDB.1;" +
            "Data Source=" + Application.StartupPath + "\\Daten;");
         dbfcon.Open();

         String query = "INSERT INTO TB_KUVG (KDNR, Kuvg_id) " +
            "VALUES(?,?)";
         OleDbCommand cmd = new OleDbCommand(query, dbfcon);
         cmd.Parameters.AddWithValue("@KDNR", 1);
         cmd.Parameters.AddWithValue("@Kuvg_id", 1);
         cmd.ExecuteNonQuery();

         dbfcon.Close();

So what am I doing wrong? Is it better to use another way to write into a .dbf from c#?

You are almost doing it right. Note that parameter names are not important and would be located positionally (ie: @KDNR is added first so that it correspond to first ? placeholder). What you are missing was, if the fields you don't pass doesn't accept NULL values then you should notify the connection that instead you want "empty" values for those fields ('' for string, / / for date, 0 for numeric and vice versa). To notify the driver, you execute 'SET NULL OFF' on the same connection.

While adding it, I revised your existing code a bit:

string dataFolder = Path.Combine(Application.StartupPath, "Daten");
String query = @"INSERT INTO TB_KUVG 
          (KDNR, Kuvg_id) 
          VALUES 
          (?,?)";
using (OleDbConnection dbfcon = new OleDbConnection("Provider=VFPOLEDB;Data Source=" + dataFolder))
{
  OleDbCommand cmd = new OleDbCommand(query, dbfcon);
  cmd.Parameters.AddWithValue("@KDNR", 1);
  cmd.Parameters.AddWithValue("@Kuvg_id", 1);

  dbfcon.Open();
  new OleDbCommand("set null off",dbfcon).ExecuteNonQuery();
  cmd.ExecuteNonQuery();
  dbfcon.Close();
}

PS: Application.StartupPath might not be a good idea as it may be under "Program Files" which is read only.

PS2: It would be better if you added "VFP" tag there, instead of "DBF".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM