views:

131

answers:

2

I'm writing a database importer from our competitors to ours database:) I have a code generator which create Methods form import to our database like

public void Test_Import_Customer_1()

 // variables
 string conn;
 string sqlSelect;
 string sqlInsert;

 int extID;
 string name;
 string name2;
 DateTime date_inserted;

 sqlSelect="select id,name,date_inserted from table_competitors_1";
 oledbreader reader = new GetOledbRader(sqlString,conn);
 while (reader.read())
 {
  name=left((string)myreader["name"],50); //limitation of my field
  date_inserted=myreader["date_inserted"];
  sqlInsert=string.Format("insert into table(name,name2,date_inserted)values '{0}', '{1}', {2})",name,name2,date_inserted); //here is the problem name2 "Use of unassigned local variable"
  ExecuteSQL(sqlInsert)
 }

As different companies database has different fields i can not set value to each variable and there is a big number of tables to go one variable to next.

like

sqlSelect_Company_1 = "select name,date_inserted from table_1";
sqlSelect_Company_2 = "select name,name2 from table_2";

is there a way to override the typing of each variable one by one with default values?

A: 

No, this is not possible. You have to assign a default value to each variable. You cannot use variables that have not been initialized - they could contain random values and you certainly do not want to insert random values in your database!

What you actually want to do is this: Write a separate method for each of the databases that uses exactly the values you need. There is no other way, it is technically impossible.

If you have a very large number of target databases, there are many ways to work around this issue, but I can't quite recommend this if you are not familiar with enough background. (I'm judging from your question that you're rather new to C# and databases? Sorry if I'm wrong.)

Just write a new method for each of the databases.

mafutrct
Yes I rather new to c# but not to databases. The problem is that there is big number of versions of databases(access,fdb, gdb, mssql,mysql) And yes it think to create method for each of competitor but was hoping for some good news :)
Tomislav
Note that in practice, the CLR always initializes local variables to their default values. The rule of C# that locals must be definitely assigned before use is to prevent a common class of logic bugs, not to prevent observation of "random" initial values.
Eric Lippert
Yes, I intentionally ignored that fact to illustrate the basic issue. May I quote Raymond? Nitpicker! JK ;) I love your blog, Eric.
mafutrct
A: 

Rather than storing your parameter values in variables store them in a Dictionary object with the keys as your field names and your values/params as the values.

Create a generic method that takes a string for the tablename and the dictionary for the params. You can build up your sql string using a string builder.

Ben Robinson