Ladies_Man

save ado pls. out of mem exception

Oct 3rd, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 28.25 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, m, p;
  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()) : 3;
  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.                 int entryNum = 10;
  227.                 String valueForEntireTable = "\n\ninsert into " + tableNames[i] + "values ";
  228.  
  229.                 for (p = 0; p < entryNum; p++)
  230.                 {
  231.                     valueForEntireTable += " (";
  232.                     foreach (var ntl in colNameToTypeToLen)
  233.                     {
  234.                         string name = ntl.Item1;
  235.                         string type = ntl.Item2;
  236.                         int len = ntl.Item3;
  237.  
  238.  
  239.                         String randomShit = generateRandomEntry(type, len);
  240.                         //Console.WriteLine(randomShit);
  241.  
  242.  
  243.                         valueForEntireTable += randomShit + ", ";
  244.                         //Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
  245.                     }
  246.                     valueForEntireTable = valueForEntireTable.Remove(valueForEntireTable.Length - 2);
  247.                     valueForEntireTable += "), ";
  248.                 }
  249.                 valueForEntireTable = valueForEntireTable.Remove(valueForEntireTable.Length - 2);
  250.                    
  251.                 Console.WriteLine(valueForEntireTable);
  252.  
  253.                 Console.WriteLine();
  254.             }
  255.  
  256.             Console.WriteLine();
  257.         }
  258.  
  259.  
  260.         private static string generateRandomEntry(string type, int len)
  261.         {
  262.             int minLen = 2;
  263.             int maxLen = len;
  264.             //Random rng = new Random();
  265.  
  266.             int k = len;//rng.Next(minLen, maxLen) / 2;
  267.  
  268.             string randomBaseAlphabetNumbers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  269.             string randomBaseAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
  270.             string randomBaseNumbers = "0123456789";
  271.             string retVal = "";
  272.  
  273.             if ("int".Equals(type))
  274.                 retVal = RandomString(k, randomBaseNumbers);
  275.  
  276.             if ("nvarchar".Equals(type))
  277.             {
  278.                 retVal = "'" + RandomString(k / 3, randomBaseAlphabet) + "'";
  279.             }
  280.  
  281.             if ("varchar".Equals(type))
  282.             {
  283.                 retVal = "'" + RandomString(k / 3, randomBaseAlphabet) + "'";
  284.             }
  285.  
  286.             if ("char".Equals(type))
  287.             {
  288.                 retVal = "'" + RandomString(k, randomBaseAlphabet) + "'";
  289.             }
  290.  
  291.             if ("nchar".Equals(type))
  292.             {
  293.                 retVal = "'" + RandomString(k, randomBaseAlphabet) + "'";
  294.             }
  295.  
  296.             if ("text".Equals(type))
  297.             {
  298.                 retVal = "'" + RandomString(k / 3, randomBaseAlphabet) + "'";
  299.             }
  300.  
  301.             if ("date".Equals(type))
  302.             {
  303.                 string randDate = RandomDay().ToString();
  304.                 randDate = randDate.Remove(randDate.Length - 8);
  305.                 string[] tmp = randDate.Split('.');
  306.                 string newDate = tmp[2] + "-" + tmp[1] + "-" + tmp[0];
  307.  
  308.                 retVal = "'" + newDate + "'";
  309.             }
  310.             if ("real".Equals(type))
  311.                 retVal = GetRandomDouble(3d, 5d).ToString();
  312.  
  313.             return retVal;
  314.         }
  315.  
  316.  
  317.         private static Random random = new Random();
  318.         public static string RandomString(int length, string c)
  319.         {
  320.             string chars = c;
  321.             return new string(Enumerable.Repeat(chars, length)
  322.               .Select(s => s[random.Next(s.Length)]).ToArray());
  323.         }
  324.  
  325.         private static Random gen = new Random();
  326.         private static DateTime RandomDay()
  327.         {
  328.             DateTime start = new DateTime(1995, 10, 2);
  329.             int range = (DateTime.Today - start).Days;
  330.             return start.AddDays(gen.Next(range));
  331.         }
  332.  
  333.         private static double GetRandomDouble(double minimum, double maximum)
  334.         {
  335.             Random random = new Random();
  336.             return random.NextDouble() * (maximum - minimum) + minimum;
  337.         }
  338.  
  339. //---------------------------------------------------------
  340. //--------------------------MAIN---------------------------
  341. //---------------------------------------------------------
  342.  
  343.  
  344.         static void Main(string[] args)
  345.         {
  346.             try
  347.             {
  348.                 /*
  349. 1. создаешь в sql студии бд с таблицами
  350. 2. создаешь app.config (или он по-умолчанию создастся) где пишиешь сервер и бд для подключения.
  351. 3. в проге создаешь экземпляр соединения через строку подключения.
  352. 4. как-нибудь обрабатываешь sql команды идущие на вход в виде: 1. открыл соединение, 2. создал SqlCommand(comm, conn) (если это ins/upd/del то добавляешь параметры через addwithValue или как еще), 3. выполнил ее (через DataReader или без него), закрыл соединение (это обязательно каждый раз откр-закр).
  353. далее несвязанный уровень:
  354. 1. создал датасет, адаптер и билдер для него
  355. 2. обработал sql запрос так же, в таблицу из датасета (datatable) внес изменения (row.delete, row[x][y] = z, rows.add),
  356. 3. сделал отдельную команду которая вносит изменения в датасет (именно отдельная команда, чтоб ты "связывал" данные только когда сам захочешь).
  357. 4. вы восхитительны
  358. */
  359.  
  360.  
  361.  
  362.  
  363.                 SqlConnection connection;
  364.  
  365.                 try {
  366.                     string connectionString = ConfigurationManager.ConnectionStrings["AdoConnString"].ConnectionString;
  367.                     connection = new SqlConnection(connectionString);
  368.                     Console.WriteLine("conn has been set");
  369.                 }
  370.                 catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); return; }
  371.  
  372.                 connection.Open();
  373.  
  374.                 /*exec(new SqlCommand("SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH " +
  375.                                     "FROM INFORMATION_SCHEMA.COLUMNS " +
  376.                                     "WHERE TABLE_NAME = N'Person'", connection));*/
  377.  
  378.                 flood(new SqlCommand("select TABLE_NAME from INFORMATION_SCHEMA.TABLES", connection), connection);
  379.  
  380.                 Console.ReadLine();
  381.                
  382.  
  383.  
  384.  
  385.                 //here comes CDB
  386.                 /*
  387.                 Console.WriteLine("retrieving dicom");
  388.  
  389.                 var theFile = new EvilDICOM.Core.IO.Reading.DICOMFileReader();
  390.  
  391.                 //DicomFile("skull2.dcm");
  392.                 //theFile.Load();
  393.                 //byte[] thePixels = theFile.DataSet[DicomTags.PixelData].Values;
  394.  
  395.        
  396.  
  397.                 Image img = Image.FromFile("tex_snoop.png");
  398.                 byte[] imgAsBytes = imageToByteArray(img);
  399.                 byte[] bytesAsImg;
  400.                
  401.                 connection.Open();
  402.  
  403.                 SqlCommand insCmd;
  404.                 insCmd = new SqlCommand("saveImage", connection);
  405.                
  406.                 insCmd.CommandType = CommandType.StoredProcedure;
  407.                 insCmd.Parameters.Add("@img", SqlDbType.Image).Value = imgAsBytes;
  408.                 insCmd.Parameters.Add("@meta", SqlDbType.Text).Value = "some meta data";
  409.  
  410.                 insCmd.ExecuteNonQuery();
  411.  
  412.                 Console.WriteLine("image has been saved succesfully");
  413.                 Console.ReadLine();
  414.  
  415.  
  416.                 exec(new SqlCommand("select * from images", connection));
  417.  
  418.  
  419.                 SqlCommand readCmd = new SqlCommand("readImage", connection);
  420.  
  421.                 readCmd.CommandType = CommandType.StoredProcedure;
  422.                 readCmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
  423.  
  424.                 readCmd.ExecuteNonQuery();
  425.                 SqlDataAdapter adp = new SqlDataAdapter(readCmd);
  426.                 DataTable dTable = new DataTable();
  427.                 try
  428.                 {
  429.                     adp.Fill(dTable);
  430.                     if (dTable.Rows.Count > 0)
  431.                     {
  432.                         MemoryStream ms = new MemoryStream((byte[])dTable.Rows[0]["img_data"]);
  433.                         bytesAsImg = imageToByteArray(Image.FromStream(ms));
  434.                         Console.WriteLine("img has been retrieved");       
  435.                     }
  436.                 }
  437.                 catch (Exception ex)
  438.                 {
  439.                     Console.WriteLine(ex.Message);
  440.                 }
  441.  
  442.                 String filename = "new_snoop";
  443.                 var fs = new BinaryWriter(new FileStream(@"C:\\tmp\\" + filename + ".png", FileMode.Append, FileAccess.Write));
  444.                 fs.Write(imgAsBytes);
  445.                 fs.Close();
  446.  
  447.                 Console.ReadLine();
  448.                 */
  449.  
  450.  
  451.  
  452.                 //back to ado lab
  453.  
  454.                 Console.WriteLine("Connection has been opened.");
  455.                 Console.WriteLine("Cвязный уровень");
  456.                 Console.WriteLine("type 'help' for help");
  457.  
  458.                 string com;
  459.  
  460.                 while (true)
  461.                 {
  462.                     string table, column, q;
  463.                     Console.Write(">");
  464.                     com = Console.ReadLine();
  465.  
  466.                     if (com.Equals(""))
  467.                         continue;
  468. //=========================================================
  469. //------------------------SELECT---------------------------
  470. //=========================================================
  471.                     if ('s' == com[0])
  472.                     {
  473.                         Console.Write("->tables | * | column:");
  474.                         string subcom = Console.ReadLine();
  475.  
  476.                         if (subcom.Equals(""))
  477.                             continue;
  478.  
  479.                         if ('t' == subcom[0])
  480.                         {
  481.                             q = "select * from INFORMATION_SCHEMA.TABLES";
  482.                             connection.Open();
  483.                             SqlCommand cmd = new SqlCommand(q, connection);
  484.  
  485.                             exec(cmd);
  486.                             connection.Close();
  487.                         }
  488.  
  489.                         if ('*' == subcom[0])
  490.                         {
  491.                             Console.Write("->tablename:");
  492.                             table = Console.ReadLine();
  493.                             if (-1 == check_tablename(table, connection))
  494.                                 continue;
  495.  
  496.                             connection.Open();
  497.                             q = string.Format("select * from {0}", table);
  498.                             SqlCommand cmd = new SqlCommand(q, connection);
  499.  
  500.                             exec(cmd);
  501.                             connection.Close();
  502.                         }
  503.  
  504.                         if ('c' == subcom[0])
  505.                         {
  506.                             Console.Write("->tablename:");
  507.                             table = Console.ReadLine();
  508.                             if (-1 == check_tablename(table, connection))
  509.                                 continue;
  510.  
  511.                             Console.Write("-->column name:");
  512.                             column = Console.ReadLine();
  513.                             if (-1 == check_colname(column, table, connection))
  514.                                 continue;
  515.  
  516.                             connection.Open();
  517.                             q = string.Format("select {0} from {1}", column, table);
  518.                             SqlCommand cmd = new SqlCommand(q, connection);
  519.  
  520.                             exec(cmd);
  521.                             connection.Close();
  522.                         }
  523.  
  524.                         if (subcom.Equals("q"))
  525.                             continue;
  526.                     }
  527.  
  528.  
  529. //=========================================================
  530. //------------------------INSERT---------------------------
  531. //=========================================================
  532.                     if ('i' == com[0])
  533.                     {
  534.                         Console.Write("->tablename:");
  535.                         table = Console.ReadLine();
  536.                         if (-1 == check_tablename(table, connection))
  537.                             continue;
  538.  
  539.                         connection.Open();
  540.                         q = string.Format("select * from {0}", table);
  541.                         SqlCommand command = new SqlCommand(q, connection);
  542.                         SqlDataReader reader = command.ExecuteReader();
  543.  
  544.                         //get column names as result of simple <select*> query
  545.                         if (reader.Read())
  546.                         {
  547.  
  548.                             int fieldCount = reader.FieldCount;
  549.  
  550.                             //form query string
  551.                             q = string.Format("insert into {0} (", table);
  552.                             for (int j = 0; j < fieldCount; j++)
  553.                             {
  554.                                 q += reader.GetName(j) + ", ";
  555.                             }
  556.                             q = q.Remove(q.Length - 2);
  557.                             q += ") values (";
  558.                             for (int j = 0; j < fieldCount; j++)
  559.                             {
  560.                                 q += "@" + reader.GetName(j) + ", ";
  561.                             }
  562.                             q = q.Remove(q.Length - 2);
  563.                             q += ")";
  564.                             Console.WriteLine("Q:" + q);
  565.  
  566.  
  567.                             SqlCommand cmd = new SqlCommand(q, connection);
  568.  
  569.                             //get parameters and add to command
  570.                             for (int j = 0; j < fieldCount; j++) {
  571.                                 Console.Write("-->{0}[{1}]:", reader.GetName(j), reader.GetDataTypeName(j));
  572.                                 Object value = Console.ReadLine();
  573.  
  574.                                 cmd.Parameters.AddWithValue("@" + reader.GetName(j), value);
  575.                             }
  576.  
  577.                             reader.Close();
  578.  
  579.                             if (0 == run(cmd, connection))
  580.                                 Console.WriteLine("entry has been inserted");
  581.  
  582.                         } else {
  583.                             reader.Close();
  584.                         }
  585.                         connection.Close();
  586.                     }
  587.  
  588.  
  589. //=========================================================
  590. //------------------------DELETE---------------------------
  591. //=========================================================
  592.                     if ('d' == com[0])
  593.                     {
  594.                         Console.Write("->tablename:");
  595.                         table = Console.ReadLine();
  596.                         if (-1 == check_tablename(table, connection))
  597.                             continue;
  598.  
  599.                         connection.Open();
  600.                         q = string.Format("select * from {0}", table);
  601.                         SqlCommand command = new SqlCommand(q, connection);
  602.                         SqlDataReader reader = command.ExecuteReader();
  603.  
  604.                         if (reader.Read())
  605.                         {
  606.  
  607.                             Object[] del_values = new Object[reader.FieldCount];//array of values to delete
  608.                             int[] field_indices = new int[reader.FieldCount];//array of their indices in table
  609.                             int delete_col_num = 0, fieldCount = reader.FieldCount;
  610.  
  611.                             q = string.Format("delete {0} where ", table);
  612.  
  613.                             for (int j = 0; j < fieldCount; j++)
  614.                             {
  615.                                 Console.Write("-->del by {0}? Y/N:", reader.GetName(j));
  616.                                 string t_com = Console.ReadLine();
  617.  
  618.                                 if ('n' == t_com[0] || 'N' == t_com[0]) {
  619.                                     continue;
  620.                                 }
  621.                                 else {
  622.                                     Console.Write("-->{0}[{1}] value:", reader.GetName(j), reader.GetDataTypeName(j));
  623.                                     del_values[delete_col_num] = Console.ReadLine();
  624.  
  625.                                     field_indices[delete_col_num] = j;
  626.                                     q += reader.GetName(j) + " = @" + reader.GetName(j) + " and ";
  627.                                     delete_col_num++;
  628.                                 }
  629.                             }
  630.  
  631.                             if (0 == delete_col_num)
  632.                             {
  633.                                 Console.WriteLine("delete parameters are missing");
  634.                                 reader.Close();
  635.                                 connection.Close();
  636.                                 continue;
  637.                             }
  638.                             q = q.Remove(q.Length - 5);
  639.                             Console.WriteLine("Q:" + q);
  640.  
  641.  
  642.  
  643.                             SqlCommand cmd = new SqlCommand(q, connection);
  644.  
  645.                             for (int k = 0; k < delete_col_num; k++) {
  646.                                 cmd.Parameters.AddWithValue("@" + reader.GetName(field_indices[k]), del_values[k]);
  647.                             }
  648.                             reader.Close();
  649.  
  650.                             if (0 == run(cmd, connection))
  651.                                 Console.WriteLine("entry(-ies) has been deleted");
  652.  
  653.                         } else {
  654.                             reader.Close();
  655.                         }
  656.                         connection.Close();
  657.                     }
  658.  
  659.  
  660. //=========================================================
  661. //------------------------UPDATE---------------------------
  662. //=========================================================
  663.                     if ('u' == com[0])
  664.                     {
  665.                         Console.Write("->tablename:");
  666.                         table = Console.ReadLine();
  667.                         if (-1 == check_tablename(table, connection))
  668.                             continue;
  669.  
  670.                         connection.Open();
  671.                         q = string.Format("select * from {0}", table);
  672.                         SqlCommand command = new SqlCommand(q, connection);
  673.                         SqlDataReader reader = command.ExecuteReader();
  674.  
  675.                         if (reader.Read())
  676.                         {
  677.                             Object[] old_values = new Object[reader.FieldCount];
  678.                             int[] old_field_indices = new int[reader.FieldCount];//array of their indices in table
  679.                             Object[] new_values = new Object[reader.FieldCount];
  680.                             int[] new_field_indices = new int[reader.FieldCount];//array of their indices in table
  681.                             int new_col_num = 0, old_col_num = 0, fieldCount = reader.FieldCount;
  682.  
  683.                             q = string.Format("update {0} set ", table);
  684.  
  685.                             for (int j = 0; j < fieldCount; j++) {
  686.                                 Console.Write("-->modify {0}? Y/N:", reader.GetName(j));
  687.                                 string t_com = Console.ReadLine();
  688.  
  689.                                 if ('n' == t_com[0] || 'N' == t_com[0]) {
  690.                                     continue;
  691.                                 }
  692.                                 else {
  693.                                     Console.Write("-->{0}[{1}] value:", reader.GetName(j), reader.GetDataTypeName(j));
  694.                                     new_values[new_col_num] = Console.ReadLine();
  695.                                     new_field_indices[new_col_num] = j;
  696.                                     q += reader.GetName(j) + " = @new" + reader.GetName(j) + ", ";
  697.                                     new_col_num++;
  698.                                 }
  699.                             }
  700.                             q = q.Remove(q.Length - 2);
  701.  
  702.                             q += " where ";
  703.                             for (int j = 0; j < fieldCount; j++) {
  704.                                 Console.Write("-->by {0}? Y/N:", reader.GetName(j));
  705.                                 string t_com = Console.ReadLine();
  706.  
  707.                                 if ('n' == t_com[0] || 'N' == t_com[0]) {
  708.                                     continue;
  709.                                 }
  710.                                 else {
  711.                                     Console.Write("-->{0}[{1}] value:", reader.GetName(j), reader.GetDataTypeName(j));
  712.                                     old_values[old_col_num] = Console.ReadLine();
  713.                                     old_field_indices[old_col_num] = j;
  714.                                     q += reader.GetName(j) + " = @old" + reader.GetName(j) + " and ";
  715.                                     old_col_num++;
  716.                                 }
  717.                             }
  718.                             q = q.Remove(q.Length - 5);
  719.                             Console.WriteLine("Q:" + q);
  720.  
  721.                             if (0 == new_col_num || 0 == old_col_num)
  722.                             {
  723.                                 Console.WriteLine("delete or update parameters are missing");
  724.                                 reader.Close();
  725.                                 connection.Close();
  726.                                 continue;
  727.                             }
  728.  
  729.  
  730.  
  731.                             SqlCommand cmd = new SqlCommand(q, connection);
  732.  
  733.                             for (int k = 0; k < new_col_num; k++) {
  734.                                 cmd.Parameters.AddWithValue("@new" + reader.GetName(new_field_indices[k]), new_values[k]);
  735.                             }
  736.                             for (int k = 0; k < old_col_num; k++) {
  737.                                 cmd.Parameters.AddWithValue("@old" + reader.GetName(old_field_indices[k]), old_values[k]);
  738.                             }
  739.  
  740.                             reader.Close();
  741.  
  742.                             if (0 == run(cmd, connection))
  743.                                 Console.WriteLine("entry(-ies) has been updated");
  744.  
  745.                         } else {
  746.                             reader.Close();
  747.                         }
  748.                         connection.Close();
  749.                     }
  750.  
  751.  
  752. //=========================================================
  753. //------------------------EXPLICIT-------------------------
  754. //=========================================================
  755.                     if ('e' == com[0])
  756.                     {
  757.                         connection.Open();
  758.                        
  759.                         Console.Write("->");
  760.                         q = Console.ReadLine();
  761.                         SqlCommand cmd = new SqlCommand(q, connection);
  762.  
  763.                         exec(cmd);
  764.  
  765.                         connection.Close();
  766.                     }
  767.  
  768.                     if ('h' == com[0])
  769.                     {
  770.                         Console.WriteLine("Available commands:");
  771.                         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");
  772.                         Console.Write("\tinsert\n\t\t<table_name>\n\t\t\t<value_string>\n");
  773.                         Console.Write("\tdelete\n\t\t<table_name>\n\t\t\t<by-fields>\n");
  774.                         Console.Write("\tupdate\n\t\t<table_name>\n\t\t\t<fields to modify>\n\t\t\t\t<by-fields>\n");
  775.                         Console.WriteLine("\texplicit\n\t\t<explicit_query>\n");
  776.                         Console.WriteLine("\tПерейти на Несвязный уроень / Выйти = [q]");
  777.                     }
  778.  
  779.                     if (com.Equals("q"))
  780.                         break;
  781.  
  782.                 }
  783.  
  784.                 Console.Write("Выйти = [q]\nПерейти на Несвзный уровень = [Any_key]\nПерейти?:");
  785.                 com = Console.ReadLine();
  786.  
  787.                 if (com.Equals("q") && !com.Equals(""))
  788.                 {
  789.                     Console.WriteLine("Closing connection. App will shut down soon.");
  790.                     if (null != connection && connection.State == ConnectionState.Open)
  791.                     {
  792.                         connection.Close();
  793.                     }
  794.                    
  795.                     return;
  796.                 }
  797.                 Console.Write("\n\nНесвязный уровень\n");
  798.                 Console.WriteLine("type 'help' for help");
  799.                
  800. /*работа на несвязном уровне есть локальная работа с датасетами
  801. 1.создаешь таковой и указываешь какие в нем есть таблицы
  802. 2.создаешь адаптер которым заполняешь этот датасет
  803. 3.и билдер который сам на основании данных из адаптера -автоматически- будет генерить запросы к бд
  804. 4.сами команды изи. там ток в del/upd есть хинт что удалять/обновлять можно лишь по primary key, но даже если в Sql студии ты его накинул на таблицу, адо все равно может его не видеть и приходится явно его накидывать еще раз
  805. 5.после того как ты поработал локально с данными их нужно связать с бд. для этого нужна доп.команда adapter.Update
  806. вы восхитительны
  807. */
  808.  
  809.                 //несвязный уровень
  810.  
  811.                 DataSet cds = new DataSet("cds");
  812.  
  813.                 SqlDataAdapter adapter = new SqlDataAdapter("select * from test", connection);
  814.                 SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
  815.  
  816.                 adapter.Fill(cds, "test");
  817.  
  818.                 DataTable dt = cds.Tables["test"];
  819.                
  820.                 //table must have primary key for delete/update queries
  821.                 try {
  822.                     DataColumn[] primary_key = new DataColumn[1];
  823.                     primary_key[0] = cds.Tables["test"].Columns["id"];
  824.                     dt.PrimaryKey = primary_key;
  825.                 }
  826.                 catch (Exception e) { Console.WriteLine(e.Message); }
  827.  
  828.  
  829.                 while (true)
  830.                 {
  831.  
  832.                     Console.Write(">");
  833.                     com = Console.ReadLine();
  834.  
  835.                     if (com.Equals(""))
  836.                         continue;
  837. //=========================================================
  838. //------------------------SELECT---------------------------
  839. //=========================================================
  840.                     if ('s' == com[0])
  841.                     {
  842.                         Console.WriteLine("select * from test");
  843.                         PrintTable(cds.Tables["test"]);
  844.                     }
  845.  
  846. //=========================================================
  847. //------------------------INSERT---------------------------
  848. //=========================================================
  849.                     if ('i' == com[0])
  850.                     {
  851.                         Console.Write("->id:");
  852.                         int tid;
  853.                         try
  854.                         {
  855.                             tid = Convert.ToInt32(Console.ReadLine());
  856.                         }
  857.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  858.                        
  859.                         Console.Write("->name:");
  860.                         string tname = Console.ReadLine();
  861.                         Console.Write("->email:");
  862.                         string tmail = Console.ReadLine();
  863.  
  864.                         DataRow row = dt.NewRow();
  865.                         row[0] = tid;
  866.                         row[1] = tname;
  867.                         row[2] = tmail;
  868.  
  869.                         try { dt.Rows.Add(row); }
  870.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  871.  
  872.                         Console.WriteLine("row has been added");
  873.                     }
  874.  
  875. //=========================================================
  876. //------------------------DELETE---------------------------
  877. //=========================================================
  878.                     if ('d' == com[0])
  879.                     {
  880.                         Console.Write("->by PrimaryKey id:");
  881.                         DataRow row = null;
  882.  
  883.                         try
  884.                         {
  885.                             int tid = Convert.ToInt32(Console.ReadLine());
  886.                             row = dt.Rows.Find(tid);
  887.                         }
  888.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  889.  
  890.                         try { row.Delete(); }
  891.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  892.  
  893.                         Console.WriteLine("row has been deleted");
  894.                     }
  895.  
  896. //=========================================================
  897. //------------------------UPDATE---------------------------
  898. //=========================================================
  899.                     if ('u' == com[0])
  900.                     {
  901.  
  902.                         Console.Write("->new email:");
  903.                         string newmail = Console.ReadLine();
  904.  
  905.                         int tid, indx;
  906.                         DataRow row = null;
  907.  
  908.                         Console.Write("->by id:");
  909.                         try
  910.                         {
  911.                             tid = Convert.ToInt32(Console.ReadLine());
  912.                             row = dt.Rows.Find(tid);
  913.                             indx = dt.Rows.IndexOf(row);
  914.                         }
  915.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  916.  
  917.                         try { dt.Rows[indx]["email"] = newmail; }
  918.                         catch (Exception e) { Console.WriteLine(e.Message); continue; }
  919.  
  920.                         Console.WriteLine("row has been updated");
  921.                         continue;
  922.                     }
  923.  
  924. //=========================================================
  925. //---------------------ACCEPT-CHANGES----------------------
  926. //=========================================================
  927.                     if ('a' == com[0])
  928.                     {
  929.                         adapter.Update(cds, dt.TableName);
  930.                         Console.WriteLine("changes have been accepted");
  931.                     }
  932.  
  933.  
  934.                     if ('h' == com[0])
  935.                     {
  936.                         Console.WriteLine("Available commands:");
  937.                         Console.Write("\tselect\n\t\t* from 'test'\n");
  938.                         Console.Write("\tinsert\n\t\tinto 'test'\n\t\t\t<value_string>\n");
  939.                         Console.Write("\tdelete\n\t\t'test' by\n\t\t\t<primary_key>\n");
  940.                         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");
  941.                         Console.WriteLine("\tAccept changes to table = [a]\n");
  942.                         Console.Write("\tExit = [q]\n");
  943.                     }
  944.  
  945.                     if (com.Equals("q"))
  946.                         break;
  947.                 }
  948.  
  949.                 Console.WriteLine("Closing connection. App will shut down soon.");
  950.                 connection.Close();
  951.  
  952.         } catch(Exception e) {
  953.             Console.WriteLine(e.Message);
  954.             Console.ReadLine();
  955.             return;
  956.         }
  957.    
  958.         }
  959.  
  960.     }
  961.  
  962. }
Advertisement
Add Comment
Please, Sign In to add comment