0

I am new to C# and I am building a project to add/update a sql table using excel. I have a way of adding excel data to an existing table using parameterized queries, however I am looking for a dynamic way of doing this (I will be using manipulating multiple tables). Here is the current code I am working with.

My error shows up near the

bulkcopy.WriteToServer(reader); 

I understand that the using statement disposes of the objects after it's finished, how can I fix this?

private void button3_Click(object sender, EventArgs e)
    {
        String connection = @"Data Source=server;Initial Catalog=database;Integrated Security=True";

        using (var connection = new SqlConnection(connectionString))
        {
            var command = connection.CreateCommand();
            // This will return the table schema information
            command.CommandText = "select * from information_schema.columns where table_name = @tableName";
            command.Parameters.Add("@tableName", SqlDbType.VarChar).Value = "MyTable";
            command.CommandType = CommandType.Text;

            connection.Open();
            var columnList = new List<ColumnInfo>();
            // Loop over the results and create a ColumnInfo object for each Column in the schema.
            using (IDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo))
            {
                while (reader.Read())
                {
                    columnList.Add(new ColumnInfo().ReadFromReader(reader));
                }
            }

            string createTempCommand = "create table {0} ({1})";
            StringBuilder sb = new StringBuilder();
            // Loop over each column info object and construct the string needed for the SQL script.
            foreach (var column in columnList)
            {
                sb.Append(column.ToString());
            }

            // create temp table
            command.CommandText = string.Format(createTempCommand, "#TempTable",
                                  string.Join(",", columnList.Select(c => c.ToString()).ToArray()));
            command.ExecuteNonQuery();
            //var dataTable = new System.Data.DataTable();
            // dataTable.Load(reader);

            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
            {
                bulkCopy.DestinationTableName = "#TempTable";
                bulkCopy.WriteToServer(reader);
            }

            // update for rows/values
            //public class ColumnInfo
        }
    }

    public class ColumnInfo
    {
        public string Name { get; set; }
        public string DataType { get; set; }
        public int OrdinalPosition { get; set; }
        public bool IsNullable { get; set; }
        public string MaxLength { get; set; }

        protected string MaxLengthFormatted
        {
            // note that columns with a max length return –1.
            get { return MaxLength.Equals("-1") ? "max" : MaxLength; }
        }

        public ColumnInfo ReadFromReader(IDataReader reader)
        {
            // get the necessary information from the datareader.
            // run the SQL on your database to see all the other information available.
            this.Name = reader["COLUMN_NAME"].ToString();
            this.DataType = reader["DATA_TYPE"].ToString();
            this.OrdinalPosition = (int)reader["ORDINAL_POSITION"];
            this.IsNullable = ((string)reader["IS_NULLABLE"]) == "YES";
            this.MaxLength = reader["CHARACTER_MAXIMUM_LENGTH"].ToString();
            return this;
        }

        public override string ToString()
        {
            return string.Format("[{0}] {1}{2} {3}NULL", Name, DataType,
                MaxLength == string.Empty ? "" : "(" + MaxLengthFormatted + ")",
                IsNullable ? "" : "NOT ");
        }
    }
  • "My error shows up" - *what error shows up*? – Tim Williams Jul 09 '18 at 16:29
  • @TimWilliams "the name 'reader' does not exist in the current context" – quincident Jul 09 '18 at 16:34
  • Then don't use that `using` block but instead declare a variable for `reader` ? Or you can nest your `using` blocks.... https://stackoverflow.com/questions/1329739/nested-using-statements-in-c-sharp – Tim Williams Jul 09 '18 at 16:37
  • @TimWilliams I tried nesting the using blocks and got this error **'There is already an open DataReader associated with this Command which must be closed first.'** I also tried adding `reader.Close();` – quincident Jul 09 '18 at 17:42
  • Okay I got rid of that error, now I am receiving this one; `System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'` – quincident Jul 09 '18 at 18:01
  • Maybe you need to include the text which is getting assigned to `command.CommandText`, if that's the source of the error. We can't see that, so there's not much we can offer there. – Tim Williams Jul 09 '18 at 18:45

0 Answers0