Test SQL Connection

private void TestSqlConnection(string TableNameString, string ConnectionString)
{
 Debug.WriteLine("Generic SQL connection test started.");
 Debug.WriteLine("This subroutine will attempt to create a record in a SQL table, then delete that record.");
 Debug.WriteLine("If no errors are generated in this subroutine, the test was successful.");
 string SelectString = string.Format("sp_pkeys [{0}]", TableNameString);
 System.Data.SqlClient.SqlDataAdapter DataAdapter = new System.Data.SqlClient.SqlDataAdapter(SelectString, ConnectionString);
 System.Data.SqlClient.SqlCommandBuilder DatabaseCommandBuilder = new System.Data.SqlClient.SqlCommandBuilder(DataAdapter);
 DatabaseCommandBuilder.QuotePrefix = "[";
 DatabaseCommandBuilder.QuoteSuffix = "]";
 Data.DataTable KeysDataTable = new Data.DataTable();
 SelectString = string.Format("sp_pkeys [{0}]", TableNameString);
 DataAdapter.Fill(KeysDataTable);
 if (KeysDataTable.Rows.Count != 1) {
  Interaction.MsgBox(string.Format("This subroutine can only test a SQL table with 1 key field.  {0}The [{1}] table has {2} key fields.", ControlChars.CrLf, TableNameString, KeysDataTable.Rows.Count));
  return;
 }
 string KeyColumnName = KeysDataTable.Rows(0).Item("COLUMN_NAME");
 Data.DataTable TestDataTable = new Data.DataTable();
 SelectString = string.Format("Select * from [{0}]", TableNameString);
 DataAdapter.SelectCommand = new SqlClient.SqlCommand(SelectString, new SqlClient.SqlConnection(ConnectionString));
 DataAdapter.Fill(TestDataTable);
 Debug.WriteLine("Test dataset filled.");
 Data.DataRow NewTestDataRow = null;
 NewTestDataRow = TestDataTable.NewRow;
 foreach (Data.DataColumn TestDataColumn in TestDataTable.Columns) {
  string ColumnName = TestDataColumn.ColumnName;
  if (object.ReferenceEquals(TestDataColumn.DataType, System.Type.GetType("System.DateTime"))) {
   NewTestDataRow.Item(ColumnName) = Now;
  } else {
   NewTestDataRow.Item(ColumnName) = TestDataTable.Rows.Count;
  }
 }
 dynamic NewRowKey = NewTestDataRow.Item(KeyColumnName);
 TestDataTable.Rows.Add(NewTestDataRow);
 DataAdapter.Update(TestDataTable);
 Debug.WriteLine("Test dataset updated (row added).");
 TestDataTable.Clear();
 DataAdapter.Fill(TestDataTable);
 Data.DataColumn[] DataColumnArray = { TestDataTable.Columns(KeyColumnName) };
 TestDataTable.PrimaryKey = DataColumnArray;
 Data.DataRow RowToDelete = TestDataTable.Rows.Find(NewRowKey);
 TestDataTable.Rows(TestDataTable.Rows.IndexOf(RowToDelete)).Delete();
 Data.DataTable TableChanges = TestDataTable.GetChanges;
 DataAdapter.Update(TestDataTable);
 Debug.WriteLine("Test dataset updated (row deleted).");
 Debug.WriteLine("Generic SQL connection test ended.");
}

No comments:

Post a Comment