示例#1
0
        protected List <ResultSet> DoQuery(string sql, int capacity = 256)
        {
            AssertConnected();
            Connection.AssertStateIs(ConnectionState.Open);
            Connection.State = ConnectionState.Executing;

            // Build and send query
            var builder = new PacketBuilder(Options.Encoding);

            builder.AppendInt1((byte)Commands.Query);
            builder.AppendStringFixed(sql);
            Connection.SendPacket(builder.ToPacket(), true);

            List <ResultSet> results = null;

            do
            {
                // Read response
                var packet = Connection.ReadPacket();

                // Execute queries with no result set
                if (PacketReader.IsOkPacket(packet))
                {
                    HandleOkPacket(packet);
                    Connection.State = ConnectionState.Open;
                    return(results);
                }

                // Read column count and initialize reader
                var position    = 0;
                var columnCount = (int)PacketReader.ReadIntLengthEncoded(packet, ref position);
                var resultSet   = new ResultSet(columnCount, capacity, Options.Encoding);

                // Fetch column definitions
                Connection.State = ConnectionState.Fetching;
                for (var i = 0; i < columnCount; i++)
                {
                    resultSet.Fields.Add(FetchColumnDefinition());
                }

                HandleOkPacket(Connection.ReadPacket());

                // Fetch all data
                for (;;)
                {
                    packet = Connection.ReadPacket();
                    if (PacketReader.IsOkPacket(packet))
                    {
                        HandleOkPacket(packet);
                        break;
                    }

                    resultSet.AddBuffer(packet);
                }

                if (results == null)
                {
                    results = new List <ResultSet>();
                }
                results.Add(resultSet);
            } while (Result.Status.HasFlag(StatusFlags.MoreResultsExist));

            Connection.State = ConnectionState.Open;
            return(results);
        }