在使用参数化查询

时间:2017-01-23 20:48:07

标签: c# visual-foxpro

我创建了一个程序,从excel电子表格中提取数据并将其推送到foxpro数据库。但是,我遇到了出现重复客户端记录的问题。

这是由于一个客户与多个其他记录相关联。

我需要知道在写作之前如何检查数据库以查看特定记录是否存在,但是我正在绘制一个完整的空白。

我的代码(针对此特定类)的内容如下所示:

namespace PropertyImport
{
public class Landlord
{
    public void Import()
    {
        int IDCOUNT = 0;
        using (var exportConnection = new OleDbConnection(connectionString: Settings.ImportFrom))
        using (var importConnection = new OleDbConnection(connectionString: Settings.ImportTo))


        using (OleDbCommand exportCommand = new OleDbCommand(@"SELECT 
[clcodel salute],
[clcodel fname],
[clcodel sname]
from [export_test$]"
, exportConnection))
        using (OleDbCommand importCommand = new OleDbCommand(@"INSERT INTO CLIENT 
        (CLCODE,CLCODEDESC,CLCLASS,
        FNAME,MNAME,SNAME
        )
        VALUES 
        (?,?,?,?,?,?,?,?)",
                    importConnection))
        {
            OleDbDataReader exportReader;
            //

            importCommand.Parameters.AddWithValue("CLCODE", "");
            importCommand.Parameters.AddWithValue("CLCODEDESC", "");
            //importCommand.Parameters.AddWithValue("CLCLASS", "");
            //importCommand.Parameters.AddWithValue("NEGOTIATOR", "");
            //importCommand.Parameters.AddWithValue("TITLE", "");
            importCommand.Parameters.AddWithValue("FNAME", "");
            importCommand.Parameters.AddWithValue("MNAME", "");
            importCommand.Parameters.AddWithValue("SNAME", "");

            // Open connections to excel sheet and foxpro database
            exportConnection.Open();
            importConnection.Open();

            Console.WriteLine("Visual Foxpro connection open");
            Console.WriteLine("Writing to table");
            Console.WriteLine("...");

            int nLoopCount = 0;
            string space = " ";

            // Initiate the reader to excel
            exportReader = exportCommand.ExecuteReader();
            // Start reading
            while (exportReader != null && exportReader.Read())
            {

                //Set parameter values whilst reading from excel
                string LandTitle = exportReader.IsDBNull(0)
                    ? string.Empty
                    : Convert.ToString(exportReader.GetValue(0)).Trim();
                string LandFname = exportReader.IsDBNull(1)
                    ? string.Empty
                    : Convert.ToString(exportReader.GetValue(1)).Trim();
                string LandSname = exportReader.IsDBNull(2)
                    ? string.Empty
                    : Convert.ToString(exportReader.GetValue(2));
                string CLCODE = string.Concat(LandFname, space, LandSname, " (P)").Trim();
                Console.WriteLine("Working on record {0}, {1}", IDCOUNT, CLCODE);


                importCommand.Parameters["CLCODE"].Value = string.Concat(LandFname, space, LandSname, " (P)").Trim();
                importCommand.Parameters["CLCODEDESC"].Value = string.Concat(LandTitle, space, LandFname, space, LandSname).Trim();
                importCommand.Parameters["TITLE"].Value = LandTitle.Trim();
                importCommand.Parameters["FNAME"].Value = LandFname.Trim();
                importCommand.Parameters["SNAME"].Value = LandSname.Trim();

                try
                {
                    importCommand.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    Console.Write("Error Writing to database");
                    Console.Write(e);
                    Console.ReadKey();
                }

                // We must close and re-open the connection after a certain number of records or the OLEDB FoxPro SQL will eventually fail
                if (nLoopCount % 100 == 0)
                {
                    importConnection.Close();
                    importConnection.Open();
                }

            }

            // done
            exportConnection.Close();
            importConnection.Close();

            Console.WriteLine("Landlord Import Complete!");
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
            if (Settings.ImportPropertyPause) Console.ReadKey();

        }
    }

}

}

我想做类似的事情:

if (CLCODE exists)
{
Do not not create record
}
else
{
create record
}

1 个答案:

答案 0 :(得分:2)

约书亚 你使它变得不必要地复杂。在多用户环境中,您将遇到“检查并插入(如果不存在)”逻辑的问题。如果您认为这不是问题,您可以执行ExecuteScalar()来检查具有该clcode的行数。如果为0那么它就不存在了。

如果你这样做,那么更喜欢使用Linq。使用Linq它只是一个:

bool exists = vfpdb.Clients.Any(c=>c.ClCode == "codetocheck");

查看是否存在。

无论如何,有一个更简单的方法,这是一个真正的技巧,但一个有效。假设你在“d:\ backyard \ temp”和“d:\ temp \ myclients.xlsx”文件下有client.dbf(仅用于我选择的演示目的):

void Main()
{
    string vfpInsert = @"Insert Into client 
    (CLCODE,CLCODEDESC,CLCLASS,FNAME,MNAME,SNAME) 
    SELECT CLCODE,CLCODEDESC,CLCLASS,FNAME,MNAME,SNAME 
     from (Iif(Xmltocursor(?,'xlData') > 0, 'xlData','')) xl 
     where Not Exists
      (Select * From client c2 Where c2.CLCODE == xl.CLCODE)";

    var xml = GetExcelData();

    using (OleDbConnection con=new OleDbConnection(@"provider=VFPOLEDB;Data Source="+@"d:\backyard\temp"))
    using (OleDbCommand cmd = new OleDbCommand(vfpInsert,con))
    {
        cmd.Parameters.Add("xldata", OleDbType.VarChar).Value = xml;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

private string GetExcelData()
{
    string dataSource = @"D:\temp\myclients.xlsx";
    DataTable t = new DataTable("Clients");

    using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" +
      string.Format("Data Source={0};", dataSource) +
      "Extended Properties=\"Excel 12.0;HDR=Yes\""))
    using (OleDbCommand cmd = new OleDbCommand("Select * from [clients$]", con))
    {
        con.Open();
        t.Load(cmd.ExecuteReader());
        con.Close();
    }
    using (MemoryStream ms = new MemoryStream())
    using (var xmlwriter = XmlTextWriter.Create(ms))
    {
        t.WriteXml(xmlwriter, XmlWriteMode.WriteSchema);
        xmlwriter.Flush();
        xmlwriter.Close();
        ms.Position = 0;
        using (StreamReader streamreader = new StreamReader(ms))
        {
            return streamreader.ReadToEnd();
        }
    }
}

编辑:以下是代码的解释:

  • 从excel获取数据作为DataTable并转换为XML字符串。
  • 将XML作为参数传递给VFP插入命令。
  • 插入命令,将XML扩展为游标(几乎总是在内存表中),然后选择那些不存在的(使用ClCode)并一次性将它们插入到客户端表中。