Advertisement
Ladies_Man

ado seems to be working

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