Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 281
Sandmaann Avatar asked Oct 13 '15 12:10

Sandmaann


1 Answers

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".

like image 50
Cetin Basoz Avatar answered Sep 19 '22 12:09

Cetin Basoz