Advertisement
Ladies_Man

ado minor improvements

Dec 28th, 2015
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 20.79 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Data.SqlClient;
  7. using System.Configuration;
  8. using System.Data;
  9.  
  10. namespace ADOnet
  11. {
  12.     class Program
  13. {
  14.         private static SqlConnection connection;
  15.  
  16.         static int check_tablename(string table) {
  17.             DataTable dTable = connection.GetSchema("TABLES", new string[] { null, null, table });
  18.  
  19.             if (dTable.Rows.Count > 0) {
  20.                 return 1;
  21.             }
  22.             Console.WriteLine("table does not exist");
  23.             return -1;
  24.         }
  25.  
  26.  
  27.         static int check_colname(string colname, string table) {
  28.             DataTable dTable = connection.GetSchema("TABLES", new string[] { null, null, table });
  29.  
  30.             if (dTable.Rows.Count > 0) {
  31.  
  32.                 string q = string.Format("select * from {0}", table);
  33.                 SqlCommand command = new SqlCommand(q, connection);
  34.                 SqlDataReader reader = command.ExecuteReader();
  35.                 if (reader.Read()) {
  36.  
  37.                     int fieldCount = reader.FieldCount;
  38.                     string[] fields = new string[fieldCount];
  39.  
  40.                     for (int j = 0; j < fieldCount; j++) {
  41.                         fields[j] = reader.GetName(j);
  42.                     }
  43.  
  44.                     if (fields.Contains<String>(colname)) {
  45.                         reader.Close();
  46.                         return 1;
  47.                     }
  48.                 }
  49.                 reader.Close();
  50.             }
  51.            
  52.             Console.WriteLine("column does not exist");
  53.             return -1;
  54.         }
  55.        
  56.  
  57.         static int run(SqlCommand command) {
  58.             try {
  59.                 command.ExecuteNonQuery();
  60.             } catch (SqlException e) {
  61.                 Console.WriteLine(e.Message);
  62.                 return -1;
  63.             }
  64.             return 0;
  65.         }
  66.  
  67.  
  68.         static void exec(SqlCommand command) {
  69.             try {
  70.                 SqlDataReader reader = command.ExecuteReader();
  71.                 do {
  72.                     while (reader.Read()) {
  73.                         Object[] values = new Object[reader.FieldCount];
  74.                         int fieldCount = reader.GetValues(values);
  75.  
  76.                         for (int i = 0; i < fieldCount; i++) {
  77.                             Console.Write("\t\t{0}", values[i]);
  78.                         }
  79.                         Console.WriteLine();
  80.                     }
  81.  
  82.                 } while (reader.NextResult());
  83.  
  84.                 reader.Close();
  85.  
  86.             } catch (Exception e) { Console.WriteLine(e.Message); }
  87.  
  88.             Console.WriteLine();
  89.         }
  90.  
  91.  
  92.         static void PrintTable(DataTable dt) {
  93.             DataTableReader dtReader = dt.CreateDataReader();
  94.  
  95.             while (dtReader.Read()) {
  96.                 for (int i = 0; i < dtReader.FieldCount; i++) {
  97.                     Console.Write("\t{0}", dtReader.GetValue(i).ToString());
  98.                 }
  99.                 Console.WriteLine();
  100.             }
  101.             dtReader.Close();
  102.         }
  103.  
  104. //---------------------------------------------------------
  105. //--------------------------MAIN---------------------------
  106. //---------------------------------------------------------
  107.  
  108.  
  109.         static void Main(string[] args) {
  110.             try {
  111.                 string connectionString = ConfigurationManager.ConnectionStrings["AdoConnString"].ConnectionString;
  112.                 connection = new SqlConnection(connectionString);
  113.                 connection.Open();
  114.  
  115.             } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); return; }
  116.            
  117.             Console.WriteLine("Connection has been opened.");
  118.             Console.WriteLine("Cвязный уровень");
  119.             Console.WriteLine("type 'help' for help");
  120.  
  121.             string com;
  122.  
  123.             while (true) {
  124.  
  125.                 string table, column, q;
  126.                 Console.Write(">");
  127.                 com = Console.ReadLine();
  128.  
  129.                 if (com.Equals("")) continue;
  130. //=========================================================
  131. //------------------------SELECT---------------------------
  132. //=========================================================
  133.                 if ('s' == com[0]) {
  134.  
  135.                     Console.Write("->tables | * | column:");
  136.                     string subcom = Console.ReadLine();
  137.  
  138.                     if ('t' == subcom[0]) {
  139.  
  140.                         q = "select * from INFORMATION_SCHEMA.TABLES";
  141.  
  142.                         exec(new SqlCommand(q, connection));
  143.  
  144.                     }
  145.  
  146.                     if ('*' == subcom[0]) {
  147.  
  148.                         Console.Write("->tablename:");
  149.                         table = Console.ReadLine();
  150.                         if (-1 == check_tablename(table))
  151.                             continue;
  152.  
  153.                         q = string.Format("select * from {0}", table);
  154.  
  155.                         exec(new SqlCommand(q, connection));
  156.                     }
  157.  
  158.                     if ('c' == subcom[0]) {
  159.  
  160.                         Console.Write("->tablename:");
  161.                         table = Console.ReadLine();
  162.                         if (-1 == check_tablename(table))
  163.                             continue;
  164.  
  165.                         Console.Write("-->column name:");
  166.                         column = Console.ReadLine();
  167.                         if (-1 == check_colname(column, table))
  168.                             continue;
  169.  
  170.                         q = string.Format("select {0} from {1}", column, table);
  171.  
  172.                         exec(new SqlCommand(q, connection));
  173.                     }
  174.  
  175.                     if (subcom.Equals("q"))
  176.                         continue;
  177.                 }
  178.  
  179.  
  180. //=========================================================
  181. //------------------------INSERT---------------------------
  182. //=========================================================
  183.                 if ('i' == com[0]) {
  184.  
  185.                     Console.Write("->tablename:");
  186.                     table = Console.ReadLine();
  187.                     if (-1 == check_tablename(table))
  188.                         continue;
  189.  
  190.                     q = string.Format("select * from {0}", table);
  191.                     SqlCommand command = new SqlCommand(q, connection);
  192.                     SqlDataReader reader = command.ExecuteReader();
  193.                    
  194.                     //get column names as result of simple query
  195.                     if (reader.Read()) {
  196.  
  197.                         int fieldCount = reader.FieldCount;
  198.                        
  199.                         //form query string
  200.                         q = string.Format("insert into {0} (", table);
  201.                         for (int j = 0; j < fieldCount; j++) {
  202.                             q += reader.GetName(j) + ", ";
  203.                         }
  204.                         q = q.Remove(q.Length - 2);
  205.                         q += ") values (";
  206.                         for (int j = 0; j < fieldCount; j++) {
  207.                             q += "@" + reader.GetName(j) + ", ";
  208.                         }
  209.                         q = q.Remove(q.Length - 2);
  210.                         q += ")";
  211.                         Console.WriteLine("Q:" + q);
  212.  
  213.                         SqlCommand cmd = new SqlCommand(q, connection);
  214.  
  215.                         //get parameters and add to command
  216.                         for (int j = 0; j < fieldCount; j++) {
  217.                             Console.Write("-->{0}[{1}]:", reader.GetName(j), reader.GetDataTypeName(j));
  218.                             Object value = Console.ReadLine();
  219.  
  220.                             cmd.Parameters.AddWithValue("@" + reader.GetName(j), value);
  221.                         }
  222.  
  223.                         reader.Close();
  224.  
  225.                         if (0 == run(cmd))
  226.                             Console.WriteLine("entry has been inserted");
  227.  
  228.                     } else {
  229.                         reader.Close();
  230.                     }
  231.                 }
  232.  
  233.  
  234. //=========================================================
  235. //------------------------DELETE---------------------------
  236. //=========================================================
  237.                 if ('d' == com[0])
  238.                 {
  239.  
  240.                     Console.Write("->tablename:");
  241.                     table = Console.ReadLine();
  242.                     if (-1 == check_tablename(table))
  243.                         continue;
  244.  
  245.                     q = string.Format("select * from {0}", table);
  246.                     SqlCommand command = new SqlCommand(q, connection);
  247.                     SqlDataReader reader = command.ExecuteReader();
  248.  
  249.                     if (reader.Read()) {
  250.  
  251.                         Object[] del_values = new Object[reader.FieldCount];//array of values to delete
  252.                         int[] field_indices = new int[reader.FieldCount];//array of their indices in table
  253.                         int delete_col_num = 0, fieldCount = reader.FieldCount;
  254.  
  255.                         q = string.Format("delete {0} where ", table);
  256.                         for (int j = 0; j < fieldCount; j++) {
  257.                             Console.Write("-->del by {0}? Y/N:", reader.GetName(j));
  258.                             string t_com = Console.ReadLine();
  259.                            
  260.                             if ('n' == t_com[0] || 'N' == t_com[0]) {
  261.                                 continue;
  262.                             } else {
  263.                                 Console.Write("-->{0}[{1}] value:", reader.GetName(j), reader.GetDataTypeName(j));
  264.                                 del_values[delete_col_num] = Console.ReadLine();
  265.                                
  266.                                 field_indices[delete_col_num] = j;
  267.                                 q += reader.GetName(j) + " = @" + reader.GetName(j) + " and ";
  268.                                 delete_col_num++;
  269.                             }
  270.                         }
  271.  
  272.                         if (0 == delete_col_num) {
  273.                             Console.WriteLine("delete parameters are missing");
  274.                             reader.Close();
  275.                             continue;
  276.                         }
  277.                         q = q.Remove(q.Length - 5);
  278.                         Console.WriteLine("Q:" + q);
  279.                        
  280.                         SqlCommand cmd = new SqlCommand(q, connection);
  281.  
  282.                         for (int k = 0; k < delete_col_num; k++) {
  283.                             cmd.Parameters.AddWithValue("@" + reader.GetName(field_indices[k]), del_values[k]);
  284.                         }
  285.                         reader.Close();
  286.  
  287.                         if (0 == run(cmd))
  288.                             Console.WriteLine("entry(-ies) has been deleted");
  289.  
  290.                     } else {
  291.                         reader.Close();
  292.                     }
  293.                 }
  294.  
  295.  
  296. //=========================================================
  297. //------------------------UPDATE---------------------------
  298. //=========================================================
  299.                 if ('u' == com[0])
  300.                 {
  301.  
  302.                     Console.Write("->tablename:");
  303.                     table = Console.ReadLine();
  304.                     if (-1 == check_tablename(table))
  305.                         continue;
  306.  
  307.                     q = string.Format("select * from {0}", table);
  308.                     SqlCommand command = new SqlCommand(q, connection);
  309.                     SqlDataReader reader = command.ExecuteReader();
  310.  
  311.                     if (reader.Read()) {
  312.  
  313.                         Object[] old_values = new Object[reader.FieldCount];
  314.                         int[] old_field_indices = new int[reader.FieldCount];//array of their indices in table
  315.                         Object[] new_values = new Object[reader.FieldCount];
  316.                         int[] new_field_indices = new int[reader.FieldCount];//array of their indices in table
  317.                         int new_col_num = 0, old_col_num = 0, fieldCount = reader.FieldCount;
  318.  
  319.                         q = string.Format("update {0} set ", table);
  320.                         for (int j = 0; j < fieldCount; j++) {
  321.                             Console.Write("-->modify {0}? Y/N:", reader.GetName(j));
  322.                             string t_com = Console.ReadLine();
  323.  
  324.                             if ('n' == t_com[0] || 'N' == t_com[0]){
  325.                                 continue;
  326.                             } else {
  327.                                 Console.Write("-->{0}[{1}] value:", reader.GetName(j), reader.GetDataTypeName(j));
  328.                                 new_values[new_col_num] = Console.ReadLine();
  329.                                 new_field_indices[new_col_num] = j;
  330.                                 q += reader.GetName(j) + " = @new" + reader.GetName(j) + ", ";
  331.                                 new_col_num++;
  332.                             }
  333.                         }
  334.                         q = q.Remove(q.Length - 2);
  335.  
  336.                         q += " where ";
  337.                         for (int j = 0; j < fieldCount; j++) {
  338.                             Console.Write("-->by {0}? Y/N:", reader.GetName(j));
  339.                             string t_com = Console.ReadLine();
  340.  
  341.                             if ('n' == t_com[0] || 'N' == t_com[0]) {
  342.                                 continue;
  343.                             } else {
  344.                                 Console.Write("-->{0}[{1}] value:", reader.GetName(j), reader.GetDataTypeName(j));
  345.                                 old_values[old_col_num] = Console.ReadLine();
  346.                                 old_field_indices[old_col_num] = j;
  347.                                 q += reader.GetName(j) + " = @old" + reader.GetName(j) + " and ";
  348.                                 old_col_num++;
  349.                             }
  350.                         }
  351.                         q = q.Remove(q.Length - 5);
  352.                         Console.WriteLine("Q:" + q);
  353.  
  354.                         if (0 == new_col_num || 0 == old_col_num) {
  355.                             Console.WriteLine("delete or update parameters are missing");
  356.                             reader.Close();
  357.                             continue;
  358.                         }
  359.  
  360.                         SqlCommand cmd = new SqlCommand(q, connection);
  361.  
  362.                         for (int k = 0; k < new_col_num; k++) {
  363.                             cmd.Parameters.AddWithValue("@new" + reader.GetName(new_field_indices[k]), new_values[k]);
  364.                         }
  365.                         for (int k = 0; k < old_col_num; k++) {
  366.                             cmd.Parameters.AddWithValue("@old" + reader.GetName(old_field_indices[k]), old_values[k]);
  367.                         }
  368.                        
  369.                         reader.Close();
  370.  
  371.                         if (0 == run(cmd))
  372.                             Console.WriteLine("entry(-ies) has been updated");
  373.  
  374.                     } else {
  375.                         reader.Close();
  376.                     }
  377.                 }
  378.  
  379.  
  380. //=========================================================
  381. //------------------------EXPLICIT-------------------------
  382. //=========================================================
  383.                 if ('e' == com[0]) {
  384.                     Console.Write("->");
  385.                     q = Console.ReadLine();
  386.  
  387.                     exec(new SqlCommand(q, connection));
  388.                 }
  389.  
  390.                 if ('h' == com[0]) {
  391.                     Console.WriteLine("Available commands:");
  392.                     Console.Write("\tselect\n\t\ttables\n\t\t*\n\t\t\t<table_name>\n\t\tcolumn\n\t\t\t<table_name>\n\t\t\t\t<column_name>\n");
  393.                     Console.Write("\tinsert\n\t\t<table_name>\n\t\t\t<value_string>\n");
  394.                     Console.Write("\tdelete\n\t\t<table_name>\n\t\t\t<by-fields>\n");
  395.                     Console.Write("\tupdate\n\t\t<table_name>\n\t\t\t<fields to modify>\n\t\t\t\t<by-fields>\n");
  396.                     Console.WriteLine("\texplicit\n\t\t<explicit_query>\n");
  397.                     Console.WriteLine("\tПерейти на Несвязный уроень / Выйти = [q]");
  398.                 }
  399.  
  400.                 if (com.Equals("q")) break;
  401.  
  402.             }
  403.            
  404.  
  405.  
  406.  
  407.             //несвязный уровень
  408.  
  409.  
  410.             Console.Write("Выйти = [q]\nПерейти на Несвзный уровень = [Any_key]\nПерейти?:");
  411.             com = Console.ReadLine();
  412.  
  413.             if (com.Equals("q") && !com.Equals("")) {
  414.                 Console.WriteLine("Closing connection. App will shut down soon.");
  415.                 connection.Close();
  416.                 return;
  417.             }
  418.             Console.Write("\n\nCвязный уровень\n");
  419.             Console.WriteLine("type 'help' for help");
  420.  
  421.  
  422.             DataSet cds = new DataSet("cds");
  423.  
  424.             DataColumn cid = new DataColumn("cid", typeof(int));
  425.             cid.AllowDBNull = false;
  426.             cid.Unique = true;
  427.             cid.ReadOnly = true;
  428.  
  429.             DataColumn name = new DataColumn("name", typeof(string));
  430.             name.AllowDBNull = false;
  431.             name.MaxLength = 35;
  432.  
  433.             DataColumn balance = new DataColumn("balance", typeof(int));
  434.             balance.AllowDBNull = false;
  435.             balance.DefaultValue = 0;
  436.  
  437.             DataTable cdt = new DataTable("cardholders");
  438.  
  439.             //cdt.Columns.AddRange(new DataColumn[] {cid, name, balance });
  440.             //cds.Tables.Add(cdt);
  441.            
  442.  
  443.  
  444.  
  445.  
  446.             SqlDataAdapter adapter;
  447.             SqlCommandBuilder builder;
  448.             adapter = new SqlDataAdapter("select * from test", connection);
  449.             builder = new SqlCommandBuilder(adapter);
  450.             adapter.Fill(cds, "test");
  451.  
  452.             DataTable dt = cds.Tables["test"];
  453.             try {
  454.                 DataColumn[] primary_key = new DataColumn[1];
  455.                 primary_key[0] = cds.Tables["test"].Columns["id"];
  456.                 dt.PrimaryKey = primary_key;
  457.  
  458.             } catch (Exception e) { Console.WriteLine(e.Message); }
  459.  
  460.  
  461.  
  462.  
  463.  
  464.             while (true) {
  465.  
  466.                 Console.Write(">");
  467.                 com = Console.ReadLine();
  468.  
  469.                 if (com.Equals("")) continue;
  470. //=========================================================
  471. //------------------------SELECT---------------------------
  472. //=========================================================
  473.                 if ('s' == com[0]) {
  474.                     Console.WriteLine("select * from test");
  475.                     PrintTable(cds.Tables["test"]);
  476.                 }
  477.  
  478. //=========================================================
  479. //------------------------INSERT---------------------------
  480. //=========================================================
  481.                 if ('i' == com[0]) {
  482.  
  483.                     Console.Write("->id:");
  484.                     int tid;
  485.                     try {
  486.                         tid = Convert.ToInt32(Console.ReadLine());
  487.  
  488.                     } catch (Exception e) { Console.WriteLine(e.Message); continue; }
  489.  
  490.                     Console.Write("->name:");
  491.                     string tname = Console.ReadLine();
  492.                     Console.Write("->email:");
  493.                     string tmail = Console.ReadLine();
  494.  
  495.                     DataRow row = dt.NewRow();
  496.                     row[0] = tid;
  497.                     row[1] = tname;
  498.                     row[2] = tmail;
  499.  
  500.                     try {
  501.                         dt.Rows.Add(row);
  502.                         adapter.Update(cds, dt.TableName);
  503.  
  504.                     } catch (Exception e) { Console.WriteLine(e.Message); continue; }
  505.  
  506.                     Console.WriteLine("row has been added");
  507.                 }
  508.  
  509.  
  510. //=========================================================
  511. //------------------------DELETE---------------------------
  512. //=========================================================
  513.                 if ('d' == com[0]) {
  514.  
  515.                     Console.Write("->by PrimaryKey id:");
  516.                     DataRow row = null;
  517.  
  518.                     try {
  519.                         int tid = Convert.ToInt32(Console.ReadLine());
  520.                         row = dt.Rows.Find(tid);
  521.                    
  522.                     } catch (Exception e) { Console.WriteLine(e.Message); continue; }
  523.  
  524.                     try {
  525.                         row.Delete();
  526.                         adapter.Update(cds, dt.TableName);
  527.  
  528.                     } catch (Exception e) { Console.WriteLine(e.Message); continue; }
  529.  
  530.                     Console.WriteLine("row(s) has been deleted");
  531.                 }
  532.  
  533.  
  534. //=========================================================
  535. //------------------------UPDATE---------------------------
  536. //=========================================================
  537.                 if ('u' == com[0]) {
  538.  
  539.                     Console.Write("->new email:");
  540.                     string newmail = Console.ReadLine();
  541.  
  542.                     int tid, indx;
  543.                     DataRow row = null;
  544.  
  545.                     Console.Write("->by id:");
  546.                     try {
  547.                         tid = Convert.ToInt32(Console.ReadLine());
  548.                         row = dt.Rows.Find(tid);
  549.                         indx = dt.Rows.IndexOf(row);
  550.  
  551.                     } catch (Exception e) { Console.WriteLine(e.Message); continue; }
  552.  
  553.                     try {
  554.                         dt.Rows[indx]["email"] = newmail;
  555.                         adapter.Update(cds, dt.TableName);
  556.  
  557.                     } catch (Exception e){ Console.WriteLine(e.Message); continue; }
  558.                    
  559.                     Console.WriteLine("row has been updated");
  560.                     continue;
  561.                 }
  562.  
  563.  
  564.                 if ('h' == com[0]) {
  565.                     Console.WriteLine("Available commands:");
  566.                     Console.Write("\tselect\n\t\t* from 'test'\n");
  567.                     Console.Write("\tinsert\n\t\tinto 'test'\n\t\t\t<value_string>\n");
  568.                     Console.Write("\tdelete\n\t\t'test' by\n\t\t\t<primary_key>\n");
  569.                     Console.Write("\tupdate\n\t\t'test' set 'emai'\n\t\t\t<new_email>\n\t\t\t\tby\n\t\t\t\t\t<primary_key>\n");
  570.                     Console.Write("\tExit = [q]\n");
  571.                 }
  572.  
  573.                 if (com.Equals("q")) break;
  574.             }
  575.  
  576.             Console.WriteLine("Closing connection. App will shut down soon.");
  577.             connection.Close();
  578.         }
  579.     }
  580. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement