0

I an trying to do a simple task of reading from one table "tab2" in a database->save to xml and then reload it into table "tab1" both have the same structure, I asked previously and received the following code as an answer.

I am having problems I am now getting the database filed ONCE per item but with a date time stamp I don't think its writing the XML from reading the database properly I am running it twice to get the schema and once for data.

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            string ConnString = (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.accdb;Persist Security Info=False");
            using (OleDbConnection Conn = new OleDbConnection(ConnString))
            {
                //Conn.Close();//severl times connection has been open
                Conn.Open();
                DataSet ds = new DataSet();
                ds.ReadXml(@"c:\\temp\\tab2.xml");
                OleDbCommand cmd = new OleDbCommand();
                //OleDbCommand cmd1 = new OleDbCommand();
                DataTable dtCSV = new DataTable();
                dtCSV = ds.Tables[0];
                cmd.Connection = Conn;
                cmd.CommandType = CommandType.Text;
                //cmd.Parameters.Add(new OleDbParameter("@field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
                //cmd1.Connection = Conn;

                for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
                {
                    //for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
                    //{
                    //    //cmd.CommandText = ("INSERT INTO  tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
                    //}
                    cmd.Parameters.Clear();
                    if (dtCSV.Columns.Count > 1)
                    {
                        //command.Parameters.Add(new OleDbParameter("@EMPID", Convert.Tostring(empsplitIt[1])));
                        //cmd.Parameters.Add(dtCSV.Rows[row][0]);
                        cmd.Parameters.Add(new OleDbParameter("@Field1", Convert.ToString(dtCSV.Rows[row][0])));
                        cmd.Parameters.Add(new OleDbParameter("@dtCSV", Convert.ToString(dtCSV.Rows[row][1])));

                        cmd.CommandText = ("INSERT INTO  tab1 ( field1, field2) VALUES (? , ?)");
                        cmd.ExecuteNonQuery();
                    }

                }

                //Conn.Close();
            }
        }
        catch (Exception ex)
        {
            richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
        }

    }

    private void button2_Click(object sender, EventArgs e)
    {
        {
            string ConnString = (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");

            using (OleDbConnection Conn = new OleDbConnection(ConnString))
            {
                string strSql = "Select * from Table1"; //only launch in main
                richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";


                try
                {

                    OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\temp\\names.mdb; Persist Security Info = False");
                    OleDbCommand cmd = new OleDbCommand(strSql, con);
                    con.Open();
                    cmd.CommandType = CommandType.Text;
                    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds, "fname,sname");
                    // Extract data set to XML file 
                    ds.WriteXml(@"c:\\temp\\tab2.xml", XmlWriteMode.WriteSchema);
                    ds.WriteXml(@"c:\\temp\\tab2.xml");


                }
                catch (Exception ex)
                {
                    richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
                }

            }
        }
    }
}

I find from my code that there is two different connection strings with in it when I putin the corect spelling correcting these it now fails on the line

  dtCSV = ds.Tables[0];

with this

Error System.IndexOutOfRangeException: Cannot find table 0. at System.Data.DataTableCollection.get_Item(Int32 index) at WindowsFormsApp8.Form1.button1_Click(Object sender, EventArgs e) in

Code:

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            string ConnString = (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
            using (OleDbConnection Conn = new OleDbConnection(ConnString))
            {
                //Conn.Close();//severl times connection has been open
                Conn.Open();
                DataSet ds = new DataSet();
                ds.ReadXml(@"c:\\temp\\tabel2.xml");
                OleDbCommand cmd = new OleDbCommand();
                //OleDbCommand cmd1 = new OleDbCommand();
                DataTable dtCSV = new DataTable("tabel1");
                dtCSV = ds.Tables[0];
                cmd.Connection = Conn;
                cmd.CommandType = CommandType.Text;
                //cmd.Parameters.Add(new OleDbParameter("@field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
                //cmd1.Connection = Conn;

                for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
                {
                    //for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
                    //{
                    //    //cmd.CommandText = ("INSERT INTO  tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
                    //}
                    cmd.Parameters.Clear();
                    if (dtCSV.Columns.Count > 1)
                    {
                        //command.Parameters.Add(new OleDbParameter("@EMPID", Convert.Tostring(empsplitIt[1])));
                        //cmd.Parameters.Add(dtCSV.Rows[row][0]);
                        cmd.Parameters.Add(new OleDbParameter("@field1", Convert.ToString(dtCSV.Rows[row][0])));
                        cmd.Parameters.Add(new OleDbParameter("@field2", Convert.ToString(dtCSV.Rows[row][1])));

                        cmd.CommandText = ("INSERT INTO  tabel1 ( field1, field2) VALUES (? , ?)");
                        cmd.ExecuteNonQuery();
                    }

                }

                //Conn.Close();
            }
        }
        catch (Exception ex)
        {
            richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
        }

    }

    private void button2_Click(object sender, EventArgs e)
    {
        {
            string ConnString = (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");

            using (OleDbConnection Conn = new OleDbConnection(ConnString))
            {
                string strSql = "Select * from tabel2"; //only launch in main
                richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";


                try
                {

                    OleDbConnection con = new OleDbConnection(ConnString);
                    OleDbCommand cmd = new OleDbCommand(strSql, con);
                    con.Open();
                    cmd.CommandType = CommandType.Text;
                    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds, "fname,sname");
                    // Extract data set to XML file 
                    ds.WriteXml(@"c:\\temp\\tabel2.xml", XmlWriteMode.WriteSchema);
                    ds.WriteXml(@"c:\   \temp\\tabel2.xml");


                }
                catch (Exception ex)
                {
                    richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
                }

            }
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Data
  • 113
  • 2
  • 11
  • Remove : .ToString(). The ole driver will recognize field types especially if the xml has a schema. So some of the parameters are number so adding a string to a parameter that is a number will give an error. – jdweng Jun 24 '17 at 13:25
  • I have tried removing toString to no bassic change @jdweng – Data Jun 24 '17 at 13:32
  • Find the type(s). I used oledb a couple of weeks ago and go similar error importing an excel worksheet. oledb with Jet driver convered first column to numbers. You are using ACE which is suppose to be an improvement to Jet. Both are used a the database in Microsoft office (depending on version). Never liked excel GENERAL cell format which converts incorrectly due to JET and ACE issues. I think you have similar issue with ACE. – jdweng Jun 24 '17 at 13:38
  • Did you try the techniques mentioned at https://stackoverflow.com/questions/293311/whats-the-best-method-to-pass-parameters-to-sqlcommand @Data ? – mjwills Jun 24 '17 at 13:45
  • cmd.Parameters.Add("@fName", SqlDbType.VarChar).Value = dtCSV.Rows[row][0].ToString(); Error System.InvalidCastException: The OleDbParameterCollection only accepts non-null OleDbParameter type objects, not String objects. at System.Data.OleDb.OleDbParameterCollection.ValidateType(Object value) at System.Data.OleDb.OleDbParameterCollection.Add(Object value) at WindowsFormsApp7.Form1.button1_Click(Object sender, EventArgs e) in C:\Users @jdweng so thats the only one of the top 3 that vaguly works – Data Jun 24 '17 at 14:00
  • @mjwills Yes but not having any good fortune or luck with that trying. – Data Jun 24 '17 at 14:30
  • the next/master program will have to deal with numbers as varchar and text this is only a very small program to test it out. Still no joy!!! @mjwils – Data Jun 24 '17 at 14:48
  • Olddb only accept index numbers of parameters and not names. So the parameters have to be added in the same sequence as in the query. This will not work "Add("@fName", SqlDbType.VarChar)" Where is the command Text which is the SQL statement? See : https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx – jdweng Jun 24 '17 at 15:07
  • What do you sujest is the answer here? @jdweng This is just a small example that has to scale up to dealing witrh numbers and text this does not need to be worried about sql ingection it just has to work. I am new to c# and programing and searching databases. This is not for commerical gain I am just doing a project that has to work so far I am jumping from one problem stackflow question and the next. – Data Jun 24 '17 at 18:08
  • The parameters have to be added in same order that they are used in the command text (query). I didn't see the query in the posting. – jdweng Jun 24 '17 at 20:06
  • Just setect * from tab2 I think it was then written out to xml. There was a third autonumber coloum which I have since deteted. I did not think it was going to be this hard a task to do. @jdweng – Data Jun 24 '17 at 20:19
  • 1
    Then you don't have parameters and that is why you are getting the error if you use named parameter. The number of parameters you are adding to the command cannot exceed the number of parameters in the select. When you use "Select *" then the number of parameters matches the number of columns in the database table. The parameters don't have names (just values) and the order you add the parameter are the same order as the database table. You also can't skip a column in the database table. You can have less parameters in the command . – jdweng Jun 24 '17 at 20:38
  • Please update your post with your current code, including any recent changes you have made. – mjwills Jun 25 '17 at 01:43
  • I left the original code and added your request to the bottom of the item oks reoky with your thoughts. @mjwills – Data Jun 25 '17 at 04:16
  • Have a squiz at https://stackoverflow.com/questions/12048152/oledb-parameterized-query . See how they are calling `cmd.Parameters.Add` and then setting `.Value` on it? You need to do calls like that as well. – mjwills Jun 25 '17 at 04:52
  • cmd.Parameters.Add(new OleDbParameter("@dtCSV", Convert.ToString(dtCSV.Rows[row][0]))); cmd.Parameters.Add(new OleDbParameter("@dtCSV", Convert.ToString(dtCSV.Rows[row][1]))); Changed adds records to database but not getting my field, get Field"2 2017-06-24T22:07:04". One step closer, @mjwils – Data Jun 25 '17 at 05:33
  • Please update your question with your current code, and spell out **exactly** what isn't working with it. – mjwills Jun 25 '17 at 07:53
  • We don't edit questions to add [solved] material, please use an answer for that. I have rolled it back to the previous version. It is possible it needs rolling back further, but I can't really tell. – halfer Jun 25 '17 at 21:45

0 Answers0