Ladies_Man

coursre db on ado

Oct 3rd, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 25.65 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Data.SqlClient;
  8. using System.Configuration;
  9. using System.Data;
  10. using System.IO;
  11. using System.Drawing;
  12.  
  13. using EvilDICOM;
  14.  
  15. namespace ADOnet
  16. {
  17.     class Program
  18. {
  19.  
  20.         static int check_tablename(string table, SqlConnection connection) {
  21.             connection.Open();
  22.             DataTable dTable = connection.GetSchema("TABLES", new string[] { null, null, table });
  23.  
  24.             if (dTable.Rows.Count > 0) {
  25.                 connection.Close();
  26.                 return 1;
  27.             }
  28.             Console.WriteLine("table does not exist");
  29.             connection.Close();
  30.             return -1;
  31.         }
  32.  
  33.  
  34.         static int check_colname(string colname, string table, SqlConnection connection)
  35.         {
  36.             connection.Open();
  37.             DataTable dTable = connection.GetSchema("TABLES", new string[] { null, null, table });
  38.  
  39.             if (dTable.Rows.Count > 0) {
  40.  
  41.                 string q = string.Format("select * from {0}", table);
  42.                 SqlCommand command = new SqlCommand(q, connection);
  43.                 SqlDataReader reader = command.ExecuteReader();
  44.                 if (reader.Read()) {
  45.  
  46.                     int fieldCount = reader.FieldCount;
  47.                     string[] fields = new string[fieldCount];
  48.  
  49.                     for (int j = 0; j < fieldCount; j++) {
  50.                         fields[j] = reader.GetName(j);
  51.                     }
  52.  
  53.                     if (fields.Contains<String>(colname)) {
  54.                         reader.Close();
  55.                         connection.Close();
  56.                         return 1;
  57.                     }
  58.                 }
  59.                 reader.Close();
  60.             }
  61.            
  62.             Console.WriteLine("column does not exist");
  63.             connection.Close();
  64.             return -1;
  65.         }
  66.        
  67.  
  68.         static int run(SqlCommand command, SqlConnection connection) {
  69.             try {
  70.                 command.ExecuteNonQuery();
  71.  
  72.             } catch (SqlException e) {
  73.                 Console.WriteLine(e.Message);
  74.                 return -1;
  75.             }
  76.             return 0;
  77.         }
  78.  
  79.  
  80.         static void exec(SqlCommand command)
  81.         {
  82.             try
  83.             {
  84.  
  85.                 SqlDataReader reader = command.ExecuteReader();
  86.                 do
  87.                 {
  88.                     while (reader.Read())
  89.                     {
  90.                         Object[] values = new Object[reader.FieldCount];
  91.                         int fieldCount = reader.GetValues(values);
  92.  
  93.                         for (int i = 0; i < fieldCount; i++)
  94.                         {
  95.                             Console.Write("\t\t{0}", values[i]);
  96.                         }
  97.                         Console.WriteLine();
  98.                     }
  99.  
  100.                 } while (reader.NextResult());
  101.  
  102.                 reader.Close();
  103.  
  104.  
  105.             }
  106.             catch (Exception e) { Console.WriteLine(e.Message); }
  107.  
  108.             Console.WriteLine();
  109.         }
  110.  
  111.         static void PrintTable(DataTable dt) {
  112.             DataTableReader dtReader = dt.CreateDataReader();
  113.  
  114.             while (dtReader.Read()) {
  115.                 for (int i = 0; i < dtReader.FieldCount; i++) {
  116.                     Console.Write("\t{0}", dtReader.GetValue(i).ToString());
  117.                 }
  118.                 Console.WriteLine();
  119.             }
  120.             dtReader.Close();
  121.         }
  122.  
  123.  
  124.  
  125.         //some new methods for CDB
  126.  
  127.  
  128.         public static byte[] imageToByteArray(System.Drawing.Image imageIn)
  129.         {
  130.             MemoryStream ms = new MemoryStream();
  131.             imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
  132.             return ms.ToArray();
  133.         }
  134.  
  135.         public static Image byteArrayToImage(byte[] byteArrayIn)
  136.         {
  137.             MemoryStream ms = new MemoryStream(byteArrayIn);
  138.             Image returnImage = Image.FromStream(ms);
  139.             return returnImage;
  140.         }
  141.  
  142.  
  143.  
  144.  
  145.  
  146.         static void flood(SqlCommand command, SqlConnection connection)
  147.         {
  148.             int i, j = 0, k, l;
  149.             string[] tableNames = new string[20];
  150.  
  151.             try
  152.             {
  153.                 SqlDataReader reader = command.ExecuteReader();
  154.                 do
  155.                 {
  156.                     while (reader.Read())
  157.                     {
  158.                         Object[] values = new Object[reader.FieldCount];
  159.                         int fieldCount = reader.GetValues(values);
  160.  
  161.                         for (i = 0; i < fieldCount; i++)
  162.                         {
  163.                             tableNames[j] = values[i].ToString();
  164.                             j++;
  165.                            
  166.  
  167.                             Console.Write("\t\t{0}", values[i]);
  168.                            
  169.                         }
  170.                         Console.WriteLine();
  171.                     }
  172.  
  173.                 } while (reader.NextResult());
  174.  
  175.                 reader.Close();
  176.  
  177.  
  178.             }
  179.             catch (Exception e) { Console.WriteLine(e.Message); }
  180.  
  181.  
  182.  
  183.  
  184.             for (i = 0; i < j; i++)
  185.             {
  186.                 //ArrayList colNames = new ArrayList();
  187.                 //ArrayList colTypes = new ArrayList();
  188.                 List<Tuple<string, string, int>> colNameToTypeToLen = new List<Tuple<string, string, int>>();
  189.  
  190.  
  191.                 String getColTypes = "SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH " +
  192.                                     "FROM INFORMATION_SCHEMA.COLUMNS " +
  193.                                     "WHERE TABLE_NAME = N'" + tableNames[i] + "'";
  194.  
  195.                 SqlCommand getColTypesCmd = new SqlCommand(getColTypes, connection);
  196.                 SqlDataReader innerTypeReader = getColTypesCmd.ExecuteReader();
  197.  
  198.                 do
  199.                 {
  200.                     while (innerTypeReader.Read())
  201.                     {
  202.                         Object[] innerValues = new Object[innerTypeReader.FieldCount];
  203.                         int innerFieldCount = innerTypeReader.GetValues(innerValues);
  204.  
  205.                         string colName = null;
  206.                         string colType = null;
  207.                         int colLen = 1;
  208.  
  209.                         colName = innerValues[0].ToString();
  210.                         colType = innerValues[1].ToString();
  211.                         colLen = !"".Equals(innerValues[2].ToString()) ?
  212.                             Int32.Parse(innerValues[2].ToString()) : 1;
  213.  
  214.                         Console.Write(" {0}_[{1}]_{2}", colName, colType, colLen);
  215.  
  216.  
  217.                         colNameToTypeToLen.Add(new Tuple<string, string, int>(colName, colType, colLen));
  218.  
  219.  
  220.                     }
  221.  
  222.                 } while (innerTypeReader.NextResult());
  223.                 innerTypeReader.Close();
  224.  
  225.  
  226.                 Console.WriteLine();
  227.             }
  228.  
  229.            
  230.  
  231.  
  232.             Console.WriteLine();
  233.         }
  234.  
  235.  
  236.         private static Random random = new Random();
  237.         public static string RandomString(int length)
  238.         {
  239.             const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  240.             return new string(Enumerable.Repeat(chars, length)
  241.               .Select(s => s[random.Next(s.Length)]).ToArray());
  242.         }
  243.  
  244. //---------------------------------------------------------
  245. //--------------------------MAIN---------------------------
  246. //---------------------------------------------------------
  247.  
  248.  
  249.         static void Main(string[] args)
  250.         {
  251.             try
  252.             {
  253.                 /*
  254. 1. создаешь в sql студии бд с таблицами
  255. 2. создаешь app.config (или он по-умолчанию создастся) где пишиешь сервер и бд для подключения.
  256. 3. в проге создаешь экземпляр соединения через строку подключения.
  257. 4. как-нибудь обрабатываешь sql команды идущие на вход в виде: 1. открыл соединение, 2. создал SqlCommand(comm, conn) (если это ins/upd/del то добавляешь параметры через addwithValue или как еще), 3. выполнил ее (через DataReader или без него), закрыл соединение (это обязательно каждый раз откр-закр).
  258. далее несвязанный уровень:
  259. 1. создал датасет, адаптер и билдер для него
  260. 2. обработал sql запрос так же, в таблицу из датасета (datatable) внес изменения (row.delete, row[x][y] = z, rows.add),
  261. 3. сделал отдельную команду которая вносит изменения в датасет (именно отдельная команда, чтоб ты "связывал" данные только когда сам захочешь).
  262. 4. вы восхитительны
  263. */
  264.  
  265.  
  266.  
  267.  
  268.                 SqlConnection connection;
  269.  
  270.                 try {
  271.                     string connectionString = ConfigurationManager.ConnectionStrings["AdoConnString"].ConnectionString;
  272.                     connection = new SqlConnection(connectionString);
  273.                     Console.WriteLine("conn has been set");
  274.                 }
  275.                 catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); return; }
  276.  
  277.                 connection.Open();
  278.  
  279.                 /*exec(new SqlCommand("SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH " +
  280.                                     "FROM INFORMATION_SCHEMA.COLUMNS " +
  281.                                     "WHERE TABLE_NAME = N'Person'", connection));*/
  282.  
  283.                 flood(new SqlCommand("select TABLE_NAME from INFORMATION_SCHEMA.TABLES", connection), connection);
  284.  
  285.                 Console.ReadLine();
  286.                
  287.  
  288.  
  289.  
  290.                 //here comes CDB
  291.                 /*
  292.                 Console.WriteLine("retrieving dicom");
  293.  
  294.                 var theFile = new EvilDICOM.Core.IO.Reading.DICOMFileReader();
  295.  
  296.                 //DicomFile("skull2.dcm");
  297.                 //theFile.Load();
  298.                 //byte[] thePixels = theFile.DataSet[DicomTags.PixelData].Values;
  299.  
  300.        
  301.  
  302.                 Image img = Image.FromFile("tex_snoop.png");
  303.                 byte[] imgAsBytes = imageToByteArray(img);
  304.                 byte[] bytesAsImg;
  305.                
  306.                 connection.Open();
  307.  
  308.                 SqlCommand insCmd;
  309.                 insCmd = new SqlCommand("saveImage", connection);
  310.                
  311.                 insCmd.CommandType = CommandType.StoredProcedure;
  312.                 insCmd.Parameters.Add("@img", SqlDbType.Image).Value = imgAsBytes;
  313.                 insCmd.Parameters.Add("@meta", SqlDbType.Text).Value = "some meta data";
  314.  
  315.                 insCmd.ExecuteNonQuery();
  316.  
  317.                 Console.WriteLine("image has been saved succesfully");
  318.                 Console.ReadLine();
  319.  
  320.  
  321.                 exec(new SqlCommand("select * from images", connection));
  322.  
  323.  
  324.                 SqlCommand readCmd = new SqlCommand("readImage", connection);
  325.  
  326.                 readCmd.CommandType = CommandType.StoredProcedure;
  327.                 readCmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
  328.  
  329.                 readCmd.ExecuteNonQuery();
  330.                 SqlDataAdapter adp = new SqlDataAdapter(readCmd);
  331.                 DataTable dTable = new DataTable();
  332.                 try
  333.                 {
  334.                     adp.Fill(dTable);
  335.                     if (dTable.Rows.Count > 0)
  336.                     {
  337.                         MemoryStream ms = new MemoryStream((byte[])dTable.Rows[0]["img_data"]);
  338.                         bytesAsImg = imageToByteArray(Image.FromStream(ms));
  339.                         Console.WriteLine("img has been retrieved");       
  340.                     }
  341.                 }
  342.                 catch (Exception ex)
  343.                 {
  344.                     Console.WriteLine(ex.Message);
  345.                 }
  346.  
  347.                 String filename = "new_snoop";
  348.                 var fs = new BinaryWriter(new FileStream(@"C:\\tmp\\" + filename + ".png", FileMode.Append, FileAccess.Write));
  349.                 fs.Write(imgAsBytes);
  350.                 fs.Close();
  351.  
  352.                 Console.ReadLine();
  353.                 */
  354.  
  355.  
  356.  
  357.                 //back to ado lab
  358.  
  359.                 Console.WriteLine("Connection has been opened.");
  360.                 Console.WriteLine("Cвязный уровень");
  361.                 Console.WriteLine("type 'help' for help");
  362.  
  363.                 string com;
  364.  
  365.                 while (true)
  366.                 {
  367.                     string table, column, q;
  368.                     Console.Write(">");
  369.                     com = Console.ReadLine();
  370.  
  371.                     if (com.Equals(""))
  372.                         continue;
  373. //=========================================================
  374. //------------------------SELECT---------------------------
  375. //=========================================================
  376.                     if ('s' == com[0])
  377.                     {
  378.                         Console.Write("->tables | * | column:");
  379.                         string subcom = Console.ReadLine();
  380.  
  381.                         if (subcom.Equals(""))
  382.                             continue;
  383.  
  384.                         if ('t' == subcom[0])
  385.                         {
  386.                             q = "select * from INFORMATION_SCHEMA.TABLES";
  387.                             connection.Open();
  388.                             SqlCommand cmd = new SqlCommand(q, connection);
  389.  
  390.                             exec(cmd);
  391.                             connection.Close();
  392.                         }
  393.  
  394.                         if ('*' == subcom[0])
  395.                         {
  396.                             Console.Write("->tablename:");
  397.                             table = Console.ReadLine();
  398.                             if (-1 == check_tablename(table, connection))
  399.                                 continue;
  400.  
  401.                             connection.Open();
  402.                             q = string.Format("select * from {0}", table);
  403.                             SqlCommand cmd = new SqlCommand(q, connection);
  404.  
  405.                             exec(cmd);
  406.                             connection.Close();
  407.                         }
  408.  
  409.                         if ('c' == subcom[0])
  410.                         {
  411.                             Console.Write("->tablename:");
  412.                             table = Console.ReadLine();
  413.                             if (-1 == check_tablename(table, connection))
  414.                                 continue;
  415.  
  416.                             Console.Write("-->column name:");
  417.                             column = Console.ReadLine();
  418.                             if (-1 == check_colname(column, table, connection))
  419.                                 continue;
  420.  
  421.                             connection.Open();
  422.                             q = string.Format("select {0} from {1}", column, table);
  423.                             SqlCommand cmd = new SqlCommand(q, connection);
  424.  
  425.                             exec(cmd);
  426.                             connection.Close();
  427.                         }
  428.  
  429.                         if (subcom.Equals("q"))
  430.                             continue;
  431.                     }
  432.  
  433.  
  434. //=========================================================
  435. //------------------------INSERT---------------------------
  436. //=========================================================
  437.                     if ('i' == com[0])
  438.                     {
  439.                         Console.Write("->tablename:");
  440.                         table = Console.ReadLine();
  441.                         if (-1 == check_tablename(table, connection))
  442.                             continue;
  443.  
  444.                         connection.Open();
  445.                         q = string.Format("select * from {0}", table);
  446.                         SqlCommand command = new SqlCommand(q, connection);
  447.                         SqlDataReader reader = command.ExecuteReader();
  448.  
  449.                         //get column names as result of simple <select*> query
  450.                         if (reader.Read())
  451.                         {
  452.  
  453.                             int fieldCount = reader.FieldCount;
  454.  
  455.                             //form query string
  456.                             q = string.Format("insert into {0} (", table);
  457.                             for (int j = 0; j < fieldCount; j++)
  458.                             {
  459.                                 q += reader.GetName(j) + ", ";
  460.                             }
  461.                             q = q.Remove(q.Length - 2);
  462.                             q += ") values (";
  463.                             for (int j = 0; j < fieldCount; j++)
  464.                             {
  465.                                 q += "@" + reader.GetName(j) + ", ";
  466.                             }
  467.                             q = q.Remove(q.Length - 2);
  468.                             q += ")";
  469.                             Console.WriteLine("Q:" + q);
  470.  
  471.  
  472.                             SqlCommand cmd = new SqlCommand(q, connection);
  473.  
  474.                             //get parameters and add to command
  475.                             for (int j = 0; j < fieldCount; j++) {
  476.                                 Console.Write("-->{0}[{1}]:", reader.GetName(j), reader.GetDataTypeName(j));
  477.                                 Object value = Console.ReadLine();
  478.  
  479.                                 cmd.Parameters.AddWithValue("@" + reader.GetName(j), value);
  480.                             }
  481.  
  482.                             reader.Close();
  483.  
  484.                             if (0 == run(cmd, connection))
  485.                                 Console.WriteLine("entry has been inserted");
  486.  
  487.                         } else {
  488.                             reader.Close();
  489.                         }
  490.                         connection.Close();
  491.                     }
  492.  
  493.  
  494. //=========================================================
  495. //------------------------DELETE---------------------------
  496. //=========================================================
  497.                     if ('d' == com[0])
  498.                     {
  499.                         Console.Write("->tablename:");
  500.                         table = Console.ReadLine();
  501.                         if (-1 == check_tablename(table, connection))
  502.                             continue;
  503.  
  504.                         connection.Open();
  505.                         q = string.Format("select * from {0}", table);
  506.                         SqlCommand command = new SqlCommand(q, connection);
  507.                         SqlDataReader reader = command.ExecuteReader();
  508.  
  509.                         if (reader.Read())
  510.                         {
  511.  
  512.                             Object[] del_values = new Object[reader.FieldCount];//array of values to delete
  513.                             int[] field_indices = new int[reader.FieldCount];//array of their indices in table
  514.                             int delete_col_num = 0, fieldCount = reader.FieldCount;
  515.  
  516.                             q = string.Format("delete {0} where ", table);
  517.  
  518.                             for (int j = 0; j < fieldCount; j++)
  519.                             {
  520.                                 Console.Write("-->del by {0}? Y/N:", reader.GetName(j));
  521.                                 string t_com = Console.ReadLine();
  522.  
  523.                                 if ('n' == t_com[0] || 'N' == t_com[0]) {
  524.                                     continue;
  525.                                 }
  526.                                 else {
  527.                                     Console.Write("-->{0}[{1}] value:", reader.GetName(j), reader.GetDataTypeName(j));
  528.                                     del_values[delete_col_num] = Console.ReadLine();
  529.  
  530.                                     field_indices[delete_col_num] = j;
  531.                                     q += reader.GetName(j) + " = @" + reader.GetName(j) + " and ";
  532.                                     delete_col_num++;
  533.                                 }
  534.                             }
  535.  
  536.                             if (0 == delete_col_num)
  537.                             {
  538.                                 Console.WriteLine("delete parameters are missing");
  539.                                 reader.Close();
  540.                                 connection.Close();
  541.                                 continue;
  542.                             }
  543.                             q = q.Remove(q.Length - 5);
  544.                             Console.WriteLine("Q:" + q);
  545.  
  546.  
  547.  
  548.                             SqlCommand cmd = new SqlCommand(q, connection);
  549.  
  550.                             for (int k = 0; k < delete_col_num; k++) {
  551.                                 cmd.Parameters.AddWithValue("@" + reader.GetName(field_indices[k]), del_values[k]);
  552.                             }
  553.                             reader.Close();
  554.  
  555.                             if (0 == run(cmd, connection))
  556.                                 Console.WriteLine("entry(-ies) has been deleted");
  557.  
  558.                         } else {
  559.                             reader.Close();
  560.                         }
  561.                         connection.Close();
  562.                     }
  563.  
  564.  
  565. //=========================================================
  566. //------------------------UPDATE---------------------------
  567. //=========================================================
  568.                     if ('u' == com[0])
  569.                     {
  570.                         Console.Write("->tablename:");
  571.                         table = Console.ReadLine();
  572.                         if (-1 == check_tablename(table, connection))
  573.                             continue;
  574.  
  575.                         connection.Open();
  576.                         q = string.Format("select * from {0}", table);
  577.                         SqlCommand command = new SqlCommand(q, connection);
  578.                         SqlDataReader reader = command.ExecuteReader();
  579.  
  580.                         if (reader.Read())
  581.                         {
  582.                             Object[] old_values = new Object[reader.FieldCount];
  583.                             int[] old_field_indices = new int[reader.FieldCount];//array of their indices in table
  584.                             Object[] new_values = new Object[reader.FieldCount];
  585.                             int[] new_field_indices = new int[reader.FieldCount];//array of their indices in table
  586.                             int new_col_num = 0, old_col_num = 0, fieldCount = reader.FieldCount;
  587.  
  588.                             q = string.Format("update {0} set ", table);
  589.  
  590.                             for (int j = 0; j < fieldCount; j++) {
  591.                                 Console.Write("-->modify {0}? Y/N:", reader.GetName(j));
  592.                                 string t_com = Console.ReadLine();
  593.  
  594.                                 if ('n' == t_com[0] || 'N' == t_com[0]) {
  595.                                     continue;
  596.                                 }
  597.                                 else {
  598.                                     Console.Write("-->{0}[{1}] value:", reader.GetName(j), reader.GetDataTypeName(j));
  599.                                     new_values[new_col_num] = Console.ReadLine();
  600.                                     new_field_indices[new_col_num] = j;
  601.                                     q += reader.GetName(j) + " = @new" + reader.GetName(j) + ", ";
  602.                                     new_col_num++;
  603.                                 }
  604.                             }
  605.                             q = q.Remove(q.Length - 2);
  606.  
  607.                             q += " where ";
  608.                             for (int j = 0; j < fieldCount; j++) {
  609.                                 Console.Write("-->by {0}? Y/N:", reader.GetName(j));
  610.                                 string t_com = Console.ReadLine();
  611.  
  612.                                 if ('n' == t_com[0] || 'N' == t_com[0]) {
  613.                                     continue;
  614.                                 }
  615.                                 else {
  616.                                     Console.Write("-->{0}[{1}] value:", reader.GetName(j), reader.GetDataTypeName(j));
  617.                                     old_values[old_col_num] = Console.ReadLine();
  618.                                     old_field_indices[old_col_num] = j;
  619.                                     q += reader.GetName(j) + " = @old" + reader.GetName(j) + " and ";
  620.                                     old_col_num++;
  621.                                 }
  622.                             }
  623.                             q = q.Remove(q.Length - 5);
  624.                             Console.WriteLine("Q:" + q);
  625.  
  626.                             if (0 == new_col_num || 0 == old_col_num)
  627.                             {
  628.                                 Console.WriteLine("delete or update parameters are missing");
  629.                                 reader.Close();
  630.                                 connection.Close();
  631.                                 continue;
  632.                             }
  633.  
  634.  
  635.  
  636.                             SqlCommand cmd = new SqlCommand(q, connection);
  637.  
  638.                             for (int k = 0; k < new_col_num; k++) {
  639.                                 cmd.Parameters.AddWithValue("@new" + reader.GetName(new_field_indices[k]), new_values[k]);
  640.                             }
  641.                             for (int k = 0; k < old_col_num; k++) {
  642.                                 cmd.Parameters.AddWithValue("@old" + reader.GetName(old_field_indices[k]), old_values[k]);
  643.                             }
  644.  
  645.                             reader.Close();
  646.  
  647.                             if (0 == run(cmd, connection))
  648.                                 Console.WriteLine("entry(-ies) has been updated");
  649.  
  650.                         } else {
  651.                             reader.Close();
  652.                         }
  653.                         connection.Close();
  654.                     }
  655.  
  656.  
  657. //=========================================================
  658. //------------------------EXPLICIT-------------------------
  659. //=========================================================
  660.                     if ('e' == com[0])
  661.                     {
  662.                         connection.Open();
  663.                        
  664.                         Console.Write("->");
  665.                         q = Console.ReadLine();
  666.                         SqlCommand cmd = new SqlCommand(q, connection);
  667.  
  668.                         exec(cmd);
  669.  
  670.                         connection.Close();
  671.                     }
  672.  
  673.                     if ('h' == com[0])
  674.                     {
  675.                         Console.WriteLine("Available commands:");
  676.                         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");
  677.                         Console.Write("\tinsert\n\t\t<table_name>\n\t\t\t<value_string>\n");
  678.                         Console.Write("\tdelete\n\t\t<table_name>\n\t\t\t<by-fields>\n");
  679.                         Console.Write("\tupdate\n\t\t<table_name>\n\t\t\t<fields to modify>\n\t\t\t\t<by-fields>\n");
  680.                         Console.WriteLine("\texplicit\n\t\t<explicit_query>\n");
  681.                         Console.WriteLine("\tПерейти на Несвязный уроень / Выйти = [q]");
  682.                     }
  683.  
  684.                     if (com.Equals("q"))
  685.                         break;
  686.  
  687.                 }
  688.  
  689.                 Console.Write("Выйти = [q]\nПерейти на Несвзный уровень = [Any_key]\nПерейти?:");
  690.                 com = Console.ReadLine();
  691.  
  692.                 if (com.Equals("q") && !com.Equals(""))
  693.                 {
  694.                     Console.WriteLine("Closing connection. App will shut down soon.");
  695.                     if (null != connection && connection.State == ConnectionState.Open)
  696.                     {
  697.                         connection.Close();
  698.                     }
  699.                    
  700.                     return;
  701.                 }
  702.                 Console.Write("\n\nНесвязный уровень\n");
  703.                 Console.WriteLine("type 'help' for help");
  704.                
  705. /*работа на несвязном уровне есть локальная работа с датасетами
  706. 1.создаешь таковой и указываешь какие в нем есть таблицы
  707. 2.создаешь адаптер которым заполняешь этот датасет
  708. 3.и билдер который сам на основании данных из адаптера -автоматически- будет генерить запросы к бд
  709. 4.сами команды изи. там ток в del/upd есть хинт что удалять/обновлять можно лишь по primary key, но даже если в Sql студии ты его накинул на таблицу, адо все равно может его не видеть и приходится явно его накидывать еще раз
  710. 5.после того как ты поработал локально с данными их нужно связать с бд. для этого нужна доп.команда adapter.Update
  711. вы восхитительны
  712. */
  713.  
  714.                 //несвязный уровень
  715.  
  716.                 DataSet cds = new DataSet("cds");
  717.  
  718.                 SqlDataAdapter adapter = new SqlDataAdapter("select * from test", connection);
  719.                 SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
  720.  
  721.                 adapter.Fill(cds, "test");
  722.  
  723.                 DataTable dt = cds.Tables["test"];
  724.                
  725.                 //table must have primary key for delete/update queries
  726.                 try {
  727.                     DataColumn[] primary_key = new DataColumn[1];
  728.                     primary_key[0] = cds.Tables["test"].Columns["id"];
  729.                     dt.PrimaryKey = primary_key;
  730.                 }
  731.                 catch (Exception e) { Console.WriteLine(e.Message); }
  732.  
  733.  
  734.                 while (true)
  735.                 {
  736.  
  737.                     Console.Write(">");
  738.                     com = Console.ReadLine();
  739.  
  740.                     if (com.Equals(""))
  741.                         continue;
  742. //=========================================================
  743. //------------------------SELECT---------------------------
  744. //=========================================================
  745.                     if ('s' == com[0])
  746.                     {
  747.                         Console.WriteLine("select * from test");
  748.                         PrintTable(cds.Tables["test"]);
  749.                     }
  750.  
  751. //=========================================================
  752. //------------------------INSERT---------------------------
  753. //=========================================================
  754.                     if ('i' == com[0])
  755.                     {
  756.                         Console.Write("->id:");
  757.                         int tid;
  758.                         try
  759.                         {
  760.                             tid = Convert.ToInt32(Console.ReadLine());
  761.                         }
  762.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  763.                        
  764.                         Console.Write("->name:");
  765.                         string tname = Console.ReadLine();
  766.                         Console.Write("->email:");
  767.                         string tmail = Console.ReadLine();
  768.  
  769.                         DataRow row = dt.NewRow();
  770.                         row[0] = tid;
  771.                         row[1] = tname;
  772.                         row[2] = tmail;
  773.  
  774.                         try { dt.Rows.Add(row); }
  775.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  776.  
  777.                         Console.WriteLine("row has been added");
  778.                     }
  779.  
  780. //=========================================================
  781. //------------------------DELETE---------------------------
  782. //=========================================================
  783.                     if ('d' == com[0])
  784.                     {
  785.                         Console.Write("->by PrimaryKey id:");
  786.                         DataRow row = null;
  787.  
  788.                         try
  789.                         {
  790.                             int tid = Convert.ToInt32(Console.ReadLine());
  791.                             row = dt.Rows.Find(tid);
  792.                         }
  793.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  794.  
  795.                         try { row.Delete(); }
  796.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  797.  
  798.                         Console.WriteLine("row has been deleted");
  799.                     }
  800.  
  801. //=========================================================
  802. //------------------------UPDATE---------------------------
  803. //=========================================================
  804.                     if ('u' == com[0])
  805.                     {
  806.  
  807.                         Console.Write("->new email:");
  808.                         string newmail = Console.ReadLine();
  809.  
  810.                         int tid, indx;
  811.                         DataRow row = null;
  812.  
  813.                         Console.Write("->by id:");
  814.                         try
  815.                         {
  816.                             tid = Convert.ToInt32(Console.ReadLine());
  817.                             row = dt.Rows.Find(tid);
  818.                             indx = dt.Rows.IndexOf(row);
  819.                         }
  820.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  821.  
  822.                         try { dt.Rows[indx]["email"] = newmail; }
  823.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  824.  
  825.                         Console.WriteLine("row has been updated");
  826.                         continue;
  827.                     }
  828.  
  829. //=========================================================
  830. //---------------------ACCEPT-CHANGES----------------------
  831. //=========================================================
  832.                     if ('a' == com[0])
  833.                     {
  834.                         adapter.Update(cds, dt.TableName);
  835.                         Console.WriteLine("changes have been accepted");
  836.                     }
  837.  
  838.  
  839.                     if ('h' == com[0])
  840.                     {
  841.                         Console.WriteLine("Available commands:");
  842.                         Console.Write("\tselect\n\t\t* from 'test'\n");
  843.                         Console.Write("\tinsert\n\t\tinto 'test'\n\t\t\t<value_string>\n");
  844.                         Console.Write("\tdelete\n\t\t'test' by\n\t\t\t<primary_key>\n");
  845.                         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");
  846.                         Console.WriteLine("\tAccept changes to table = [a]\n");
  847.                         Console.Write("\tExit = [q]\n");
  848.                     }
  849.  
  850.                     if (com.Equals("q"))
  851.                         break;
  852.                 }
  853.  
  854.                 Console.WriteLine("Closing connection. App will shut down soon.");
  855.                 connection.Close();
  856.  
  857.         } catch(Exception e) {
  858.             Console.WriteLine(e.Message);
  859.             Console.ReadLine();
  860.             return;
  861.         }
  862.    
  863.         }
  864.  
  865.     }
  866.  
  867. }
Advertisement
Add Comment
Please, Sign In to add comment