ExecuteReader() public method

Sends the CommandText to the Connection and builds a NpgsqlDataReader.
public ExecuteReader ( ) : Npgsql.NpgsqlDataReader
return Npgsql.NpgsqlDataReader
コード例 #1
3
 public static List<GrilleRabais> getListGrilleRistourne(String query)
 {
     NpgsqlConnection con = Connexion.Connection();
     try
     {
         List<GrilleRabais> l = new List<GrilleRabais>();
         NpgsqlCommand Lcmd = new NpgsqlCommand(query, con);
         NpgsqlDataReader lect = Lcmd.ExecuteReader();
         if (lect.HasRows)
         {
             while (lect.Read())
             {
                 GrilleRabais a = new GrilleRabais();
                 a.Id = Convert.ToInt64(lect["id"].ToString());
                 a.Nature = lect["nature_montant"].ToString();
                 a.Minimal = (Double)((lect["montant_minimal"] != null) ? ((!lect["montant_minimal"].ToString().Trim().Equals("")) ? lect["montant_minimal"] : 0) : 0);
                 a.Maximal = (Double)((lect["montant_maximal"] != null) ? ((!lect["montant_maximal"].ToString().Trim().Equals("")) ? lect["montant_maximal"] : 0) : 0);
                 a.Montant = (Double)((lect["montant_ristourne"] != null) ? ((!lect["montant_ristourne"].ToString().Trim().Equals("")) ? lect["montant_ristourne"] : 0) : 0);
                 a.Update = true;
                 l.Add(a);
             }
             lect.Close();
         }
         return l;
     }
     catch (NpgsqlException e)
     {
         Messages.Exception(e);
         return null;
     }
     finally
     {
         Connexion.Deconnection(con);
     }
 }
コード例 #2
1
ファイル: TextTests.cs プロジェクト: Emill/Npgsql
        public void Roundtrip()
        {
            const string expected = "Something";
            var cmd = new NpgsqlCommand("SELECT @p1, @p2, @p3, @p4", Conn);
            var p1 = new NpgsqlParameter("p1", NpgsqlDbType.Text);
            var p2 = new NpgsqlParameter("p2", NpgsqlDbType.Varchar);
            var p3 = new NpgsqlParameter("p3", DbType.String);
            var p4 = new NpgsqlParameter { ParameterName = "p4", Value = expected };
            Assert.That(p2.DbType, Is.EqualTo(DbType.String));
            Assert.That(p3.NpgsqlDbType, Is.EqualTo(NpgsqlDbType.Text));
            Assert.That(p3.DbType, Is.EqualTo(DbType.String));
            cmd.Parameters.Add(p1);
            cmd.Parameters.Add(p2);
            cmd.Parameters.Add(p3);
            cmd.Parameters.Add(p4);
            p1.Value = p2.Value = p3.Value = expected;
            var reader = cmd.ExecuteReader();
            reader.Read();

            for (var i = 0; i < cmd.Parameters.Count; i++)
            {
                Assert.That(reader.GetFieldType(i),          Is.EqualTo(typeof(string)));
                Assert.That(reader.GetString(i),             Is.EqualTo(expected));
                Assert.That(reader.GetFieldValue<string>(i), Is.EqualTo(expected));
                Assert.That(reader.GetValue(i),              Is.EqualTo(expected));
                Assert.That(reader.GetFieldValue<char[]>(i), Is.EqualTo(expected.ToCharArray()));
            }

            reader.Close();
            cmd.Dispose();
        }
コード例 #3
1
ファイル: TextTests.cs プロジェクト: Emill/Npgsql
        public void Long([Values(CommandBehavior.Default, CommandBehavior.SequentialAccess)] CommandBehavior behavior)
        {
            var builder = new StringBuilder("ABCDEééé", Conn.BufferSize);
            builder.Append('X', Conn.BufferSize);
            var expected = builder.ToString();
            ExecuteNonQuery("CREATE TEMP TABLE data (name TEXT)");
            var cmd = new NpgsqlCommand(@"INSERT INTO data (name) VALUES (@p)", Conn);
            cmd.Parameters.Add(new NpgsqlParameter("p", expected));
            cmd.ExecuteNonQuery();

            const string queryText = @"SELECT name, 'foo', name, name, name, name FROM data";
            cmd = new NpgsqlCommand(queryText, Conn);
            var reader = cmd.ExecuteReader(behavior);
            reader.Read();

            var actual = reader[0];
            Assert.That(actual, Is.EqualTo(expected));

            if (IsSequential(behavior))
                Assert.That(() => reader[0], Throws.Exception.TypeOf<InvalidOperationException>(), "Seek back sequential");
            else
                Assert.That(reader[0], Is.EqualTo(expected));

            Assert.That(reader.GetString(1), Is.EqualTo("foo"));
            Assert.That(reader.GetFieldValue<string>(2), Is.EqualTo(expected));
            Assert.That(reader.GetValue(3), Is.EqualTo(expected));
            Assert.That(reader.GetFieldValue<string>(4), Is.EqualTo(expected));
            Assert.That(reader.GetFieldValue<char[]>(5), Is.EqualTo(expected.ToCharArray()));
        }
コード例 #4
1
        private void UpdateTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("GolfID", typeof(string));
            dt.Columns.Add("Förnamn", typeof(string));
            dt.Columns.Add("Efternamn", typeof(string));

            String sql = "SELECT golf_id, förnamn, efternamn FROM medlem;";
            NpgsqlCommand command = new NpgsqlCommand(sql, GolfReception.conn);
            NpgsqlDataReader ndr = command.ExecuteReader();

            while (ndr.Read())
            {
                DataRow row = dt.NewRow();
                row["GolfID"] = ndr["golf_id"];
                row["Förnamn"] = ndr["förnamn"];
                row["Efternamn"] = ndr["efternamn"];
                dt.Rows.Add(row);
            }
            ndr.Close();

            DataView dv = new DataView(dt);
            //TODO Fix this filter, only golfId working
            dv.RowFilter = "GolfID LIKE '" + golfId_textBox.Text + "*' AND Förnamn LIKE '" + firstName_textBox.Text + "*' AND Efternamn LIKE '" + lastName_textBox.Text + "*'";

            //Set the component data
            dataGridView.DataSource = dv;

            //Set column header text
            dataGridView.Columns[0].HeaderText = "Golf-ID";
            dataGridView.Columns[1].HeaderText = "Förnamn";
            dataGridView.Columns[2].HeaderText = "Efternamn";
        }
コード例 #5
0
ファイル: SchemaTests.cs プロジェクト: ArsenShnurkov/npgsql
        public void SchemaOnly([Values(PrepareOrNot.NotPrepared, PrepareOrNot.Prepared)] PrepareOrNot prepare)
        {
            using (var conn = OpenConnection())
            {
                conn.ExecuteNonQuery("CREATE TEMP TABLE data (name TEXT)");
                using (var cmd = new NpgsqlCommand(
                    "SELECT 1 AS some_column;" +
                    "UPDATE data SET name='yo' WHERE 1=0;" +
                    "SELECT 1 AS some_other_column",
                    conn))
                {
                    if (prepare == PrepareOrNot.Prepared)
                        cmd.Prepare();
                    using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
                    {
                        Assert.That(reader.Read(), Is.False);
                        var t = reader.GetSchemaTable();
                        Assert.That(t.Rows[0]["ColumnName"], Is.EqualTo("some_column"));
                        Assert.That(reader.NextResult(), Is.True);
                        Assert.That(reader.Read(), Is.False);
                        t = reader.GetSchemaTable();
                        Assert.That(t.Rows[0]["ColumnName"], Is.EqualTo("some_other_column"));
                        Assert.That(reader.NextResult(), Is.False);
                    }

                    // Close reader in the middle
                    using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
                        reader.Read();
                }
            }
        }
コード例 #6
0
ファイル: Database.cs プロジェクト: Suui/NeuralNetwork
        public void LoadValuesFor(NeuralNetwork neuralNetwork)
        {
            var firstLayerWeights = new ValueList<double>();
            var secondLayerWeights = new ValueList<double>();

            var secondLayerThresholds = new ValueList<double>();
            var thirdLayerThresholds = new ValueList<double>();

            try
            {
                var connection = new NpgsqlConnection(ConnectionString);
                connection.Open();
                var command = new NpgsqlCommand { Connection = connection };

                command.CommandText = "SELECT weight FROM pr4_weights_layer1 ORDER BY id ASC";
                var reader = command.ExecuteReader();

                while (reader.Read())
                    firstLayerWeights.Add(reader.GetDouble(0));

                reader.Close();
                command.CommandText = "SELECT weight FROM pr4_weights_layer2 ORDER BY id ASC";
                reader = command.ExecuteReader();

                while (reader.Read())
                    secondLayerWeights.Add(reader.GetDouble(0));

                reader.Close();
                command.CommandText = "SELECT threshold FROM pr4_thresholds_layer2 ORDER BY id ASC";
                reader = command.ExecuteReader();

                while (reader.Read())
                    secondLayerThresholds.Add(reader.GetDouble(0));

                reader.Close();
                command.CommandText = "SELECT threshold FROM pr4_thresholds_layer3 ORDER BY id ASC";
                reader = command.ExecuteReader();

                while (reader.Read())
                    thirdLayerThresholds.Add(reader.GetDouble(0));

                neuralNetwork.SetWeightsForLayer(1, firstLayerWeights);
                neuralNetwork.SetWeightsForLayer(2, secondLayerWeights);

                neuralNetwork.SetThresholdsForLayer(2, secondLayerThresholds);
                neuralNetwork.SetThresholdsForLayer(3, thirdLayerThresholds);
            }
            catch (Exception)
            {
                Console.WriteLine("There was a problem loading values from the database.");
                throw;
            }
        }
コード例 #7
0
ファイル: productDAO.cs プロジェクト: kapranowroman/Tasks
       public List<Product> getList()
       {
           using (NpgsqlConnection connection = getConnection())
           {
               using (NpgsqlCommand cmd = new NpgsqlCommand(SELECT_CMD, connection))
               {
                   connection.Open();
                   List<Product> result = new List<Product>();
                   using (var reader = cmd.ExecuteReader())
                   {
                       while (reader.Read())
                       {
                           Product temp = new Product();
                           temp.id = reader.GetGuid(0);
                           temp.description = reader.GetString(1);
                           temp.productGroupID = reader.GetGuid(2);
                           temp.Unit = Units.FromName(reader.GetString(3));

                           if (!reader.IsDBNull(4))
                           {
                               temp.weight = (Decimal)reader.GetFloat(4);
                           }

                           temp.money = reader.GetDecimal(5);
                           temp.quantity = reader.GetInt32(6);
                           result.Add(temp);
                       }
                   }

                   return result;
               }
           }
       }
コード例 #8
0
ファイル: TestPerson.cs プロジェクト: nbIxMaN/MQTESTS
 public static TestPerson BuildPersonFromDataBaseData(string idPerson, string MIS)
 {
     using (NpgsqlConnection connection = Global.GetSqlConnection())
     {
         string findPatient = "SELECT * FROM public.person WHERE id_person = '" + idPerson + "'";
         NpgsqlCommand person = new NpgsqlCommand(findPatient, connection);
         using (NpgsqlDataReader personFromDataBase = person.ExecuteReader())
         {
             Person p = new Person();
             while (personFromDataBase.Read())
             {
                 //что делать с DateSpecified и Мисами?
                 if (personFromDataBase["birthday"]!= DBNull.Value)
                     p.BirthDate = Convert.ToDateTime(personFromDataBase["birthday"]);
                 if (MIS == "")
                     p.IdPatientMis = null;
                 if ((personFromDataBase["family_name"] != DBNull.Value) || (personFromDataBase["given_name"] != DBNull.Value) || (personFromDataBase["middle_name"] != DBNull.Value))
                 {
                     p.HumanName = new HumanName();
                     if (personFromDataBase["family_name"] != DBNull.Value)
                         p.HumanName.FamilyName = Convert.ToString(personFromDataBase["family_name"]);
                     if (personFromDataBase["given_name"] != DBNull.Value)
                         p.HumanName.GivenName = Convert.ToString(personFromDataBase["given_name"]);
                     if (personFromDataBase["middle_name"] != DBNull.Value)
                         p.HumanName.MiddleName = Convert.ToString(personFromDataBase["middle_name"]);
                 }
                 TestPerson pers = new TestPerson(p);
                 if (personFromDataBase["id_sex"] != DBNull.Value)
                     pers.sex = TestCoding.BuildCodingFromDataBaseData(Convert.ToString(personFromDataBase["id_sex"]));
                 return pers;
             }
         }
     }
     return null;
 }
コード例 #9
0
ファイル: CommandTests.cs プロジェクト: gencer/Npgsql2
 public void MultipleCommands(bool[] queries)
 {
     using (var conn = OpenConnection())
     {
         conn.ExecuteNonQuery("CREATE TEMP TABLE data (name TEXT)");
         var sb = new StringBuilder();
         foreach (var query in queries)
             sb.Append(query ? "SELECT 1;" : "UPDATE data SET name='yo' WHERE 1=0;");
         var sql = sb.ToString();
         foreach (var prepare in new[] {false, true})
         {
             using (var cmd = new NpgsqlCommand(sql, conn))
             {
                 if (prepare)
                     cmd.Prepare();
                 using (var reader = cmd.ExecuteReader())
                 {
                     var numResultSets = queries.Count(q => q);
                     for (var i = 0; i < numResultSets; i++)
                     {
                         Assert.That(reader.Read(), Is.True);
                         Assert.That(reader[0], Is.EqualTo(1));
                         Assert.That(reader.NextResult(), Is.EqualTo(i != numResultSets - 1));
                     }
                 }
             }
         }
     }
 }
コード例 #10
0
        // GET api/values
        public IEnumerable<string> Get()
        {
            // return new string[] { "value1", "value2" };
               var result = new List<string>();
            using (var conn = new NpgsqlConnection())
            {
                conn.ConnectionString = "PORT=5432;TIMEOUT=15;POOLING=True;MINPOOLSIZE=1;MAXPOOLSIZE=20;COMMANDTIMEOUT=20;DATABASE=pdtgis;HOST=localhost;USER ID=postgres;PASSWORD=morty";
                conn.Open();

                using (var cmd = new NpgsqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText =
                        "SELECT name,amenity, ST_AsGeoJson(way) FROM planet_osm_point WHERE amenity = \'pub\' LIMIT 10;";
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            result.Add(reader.GetString(2));
                        }
                    }
                }
            }

            return result;
        }
コード例 #11
0
ファイル: AppNavigator.cs プロジェクト: ukrasutp/Wave
        /// <summary>
        /// Обновить данные
        /// </summary>
        protected override void UpdateDefaultButton()
        {
            NpgsqlConnection npgSqlConnection = new NpgsqlConnection(WaveEnvirument.ConnectionString);
            try
            {
                npgSqlConnection.Open();

                    //формируем запрос
                    using (NpgsqlCommand sqlQuery = new NpgsqlCommand("SELECT * FROM public.object_structure;", npgSqlConnection))
                    {
                        NpgsqlDataReader reader = sqlQuery.ExecuteReader();
                        lastUpdate = DateTime.Now;

                        while (reader.Read())
                        {

                        }

                }
            }
            catch (Exception ex)
            {
            }
            finally
            {

            }
        }
コード例 #12
0
ファイル: PgSqlServer.cs プロジェクト: wallymathieu/mejram
 public IEnumerable<Routine> GetRoutines()
 {
     var list = new List<Routine>();
     using (var sqlConnection = new NpgsqlConnection(connectionString))
     {
         using (var cmd = new NpgsqlCommand(@"
     SELECT routine_name
     FROM INFORMATION_SCHEMA.routines
     WHERE
     routine_schema <> 'pg_catalog'
     and routine_schema <>'information_schema'
     ", sqlConnection))
         {
             sqlConnection.Open();
             cmd.CommandType = CommandType.Text;
             using (var reader = cmd.ExecuteReader())
             {
                 while (reader.Read())
                 {
                     list.Add(new Routine(reader.GetString(0)));
                 }
             }
         }
     }
     return list;
 }
コード例 #13
0
ファイル: Program.cs プロジェクト: ekospinach/kawaldesa
        private static void Run()
        {
            var connStr = ConfigurationManager.AppSettings["ConnectionString"];
            using(NpgsqlConnection conn = new NpgsqlConnection(connStr))
            using(NpgsqlConnection updateConn = new NpgsqlConnection(connStr))
            {
                conn.Open();
                updateConn.Open();

                // Define a query returning a single row result set
                using (NpgsqlCommand command = new NpgsqlCommand("select id, file_name, fk_file_id from source_documents where thumbnail_created = false;", conn))
                {
                    using (NpgsqlDataReader dr = command.ExecuteReader())
                    {
                        // Output rows
                        while (dr.Read())
                        {
                            CreateThumbnail((string)dr[1], (long)dr[2]);
                            using (NpgsqlCommand update = new NpgsqlCommand("update source_documents set thumbnail_created = true where id = " + dr[0], updateConn))
                            {
                                update.ExecuteNonQuery();
                            }
                        }
                    }
                }
            }
        }
コード例 #14
0
ファイル: Main.cs プロジェクト: gunchee/class-management
        public Main()
        {
            InitializeComponent();
            string str = "Uid=postgres; Password=123; server=localhost; port=5432; Database=classmanagement;";
            NpgsqlConnection conn = new NpgsqlConnection(str);
            conn.Open();
            String select = "SELECT name FROM subject";
            NpgsqlCommand select_command = new NpgsqlCommand(select, conn);
            NpgsqlDataReader reader = select_command.ExecuteReader();

            while (reader.Read())
            {
                comboBox1.Items.Add(reader[0]);
                comboBox3.Items.Add(reader[0]);
                comboBox4.Items.Add(reader[0]);
                comboBox6.Items.Add(reader[0]);
                comboBox7.Items.Add(reader[0]);
            }
            dataGridView2.Refresh();
            dataGridView2.ColumnCount = 2;
            dataGridView2.Columns[0].Name = "Name";
            dataGridView2.Columns[1].Name = "Surname";
            reader.Close();
            conn.Close();
        }
コード例 #15
0
ファイル: ManagerForm.cs プロジェクト: raymon-02/time_manager
        private void initDataListView()
        {
            dataListView.Items.Clear();

            var date = dateTimePicker.Value.Date;
            var dateQuery = "'" + date.Year + "-" + date.Month + "-" + date.Day + "'";
            var query = "SELECT Data.start_t, Data.end_t, Category.name" +
                        " FROM Data" +
                        " JOIN Mem_cat ON (Data.mem_cat_id=Mem_cat.id)" +
                        " JOIN Category ON (Mem_cat.category_id=Category.id)" +
                        " WHERE Mem_cat.member_id=" + id +
                        " AND Data.day=" + dateQuery;

            var cmd = new NpgsqlCommand(query, npgsqlConnection);
            var dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                var startTime = dr.GetTimeSpan(0);
                var endTime = dr.GetTimeSpan(1);
                var category = dr.GetString(2);

                var item = new ListViewItem(startTime.ToString());
                item.SubItems.Add(endTime.ToString());
                item.SubItems.Add(category);
                dataListView.Items.Add(item);
            }

            dr.Close();
        }
コード例 #16
0
        public static List<ModeloUsuario> ObtenerTodosUsuarios()
        {
            try
            {
                List<ModeloUsuario> usuarios = null;
                NpgsqlCommand cmd = new NpgsqlCommand("select nombre,apellido,direccion,nombreusuario,email from usuario", Conexion.conexion);
                Conexion.abrirConexion();
                NpgsqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    usuarios = new List<ModeloUsuario>();
                    while (reader.Read())
                    {
                        ModeloUsuario usuario = new ModeloUsuario();
                        usuario.nombre = reader["nombre"].ToString();
                        usuario.apellido = reader["apellido"].ToString();
                        usuario.direccion = reader["direccion"].ToString();
                        usuario.nombreUsuario = reader["nombreusuario"].ToString();
                        //usuario.contrasena = reader["contrasena"].ToString();
                       // usuario.nivelAcceso = reader["nivelacceso"].ToString();
                        usuario.email = reader["email"].ToString();
                        usuarios.Add(usuario);
                    }
                }
                Conexion.cerrarConexion();
                return usuarios;

            }
            catch (Exception ex)
            {
                throw new Exception("Hubo un error con la base de datos, intente de nuevo más tarde");
            }
        }
コード例 #17
0
ファイル: clsRightOrNot.cs プロジェクト: systemvetenskap/OG
 public string getXml(string testID)
 {
     string result = "";
     try
     {
         NpgsqlConnection conn = new NpgsqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["JE"].ConnectionString);
         conn.Open();
         NpgsqlCommand cmd = new NpgsqlCommand("SELECT  id, xml_answer as qXml FROM completed_test  where id= @testID", conn);
         cmd.Parameters.AddWithValue("testID", int.Parse(testID));
         //cmd.Parameters.Add("testID", testID);
         NpgsqlDataReader dr = cmd.ExecuteReader();
         if (dr.Read())
         {
             result = dr["qXml"].ToString();
         }
         dr.Close();
         conn.Close();
         return result.TrimStart();
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.ToString());
     }
     return "";
 }
コード例 #18
0
ファイル: clsRightOrNot.cs プロジェクト: systemvetenskap/OG
        public string canHandIn(string testID)
        {
            string result = "";
            NpgsqlConnection conn = new NpgsqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["JE"].ConnectionString);
            conn.Open();
            NpgsqlCommand cmd = new NpgsqlCommand("SELECT  id, start_time, end_time FROM completed_test  where id= @testID ", conn);
            cmd.Parameters.AddWithValue("testID", int.Parse(testID));
            //cmd.Parameters.Add("testID", testID);
            NpgsqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                result = dr["start_time"].ToString();
                if (dr["end_time"] != null)
                {

                }
            }
            else
            {
                dr.Close();
                conn.Close();
                return "FINNS INGET TEST";
            }
            dr.Close();
            conn.Close();
            TimeSpan diffTime = DateTime.Parse(DateTime.Now.ToString()) - DateTime.Parse(result);
            if (diffTime.TotalMinutes > 29)
            {
                return "TIDEN DROG ÖVER";
            }
            return "OK";
        }
        static int limitForPointView = 10000; //количество точек для отображения на Zedgraph

        #endregion Fields

        #region Methods

        public static List<List<string>> GetAllExperimentGroups(ADatabase db)
        {
            try
            {
                List<List<string>> result = new List<List<string>>();
                string sql = "SELECT  experimentgroups.experimentgroupsid, experimentgroups.datestart, experimentgroups.datestop - experimentgroups.datestart,(select Count(*) from experiments where experimentgroups.experimentgroupsid = experiments.experimentgroupsid) as cn ,(select Count(*) as pointcount from parametersvalues where  parametersvalues.experimentid = (select experimentid from experiments where experiments.experimentgroupsID = experimentgroups.experimentgroupsID FETCH FIRST ROW ONLY)  and parametersvalues.parametersid = 1), experimentgroups.powerdelay, experimentgroups.commdelay, experimentgroups.description FROM ExperimentGroups order by experimentgroups.experimentgroupsid";
                NpgsqlCommand readCommand = new NpgsqlCommand(sql, db.Connection);
                NpgsqlDataReader myreader = readCommand.ExecuteReader();
                List<string> line;
                while (myreader.Read())
                {
                    line = new List<string>();
                    // load the combobox with the names of the people inside.
                    // myreader[0] reads from the 1st Column
                    for (int i = 0; i < myreader.FieldCount; i++)
                    {
                        line.Add(myreader[i].ToString());
                    }

                    result.Add(line);
                }
                myreader.Close(); // we are done with the reader
                return result;
            }
            catch (Exception ex)
            {
                FileWorker.WriteEventFile(DateTime.Now, "DatabaseWorker", "GetAllExperimentGroups", ex.Message);
                return null;
            }
        }
コード例 #20
0
ファイル: TestReferralSurvey.cs プロジェクト: nbIxMaN/MQTESTS
 public static TestReferralSurvey BuildAdditionalFromDataBaseData(string idReferral)
 {
     using (NpgsqlConnection connection = Global.GetSqlConnection())
     {
         string findPatient = "SELECT id_survey_organ, survey_comment, id_survey_type FROM public.referral WHERE id_referral = '" + idReferral + "' ORDER BY id_referral DESC LIMIT 1";
         NpgsqlCommand person = new NpgsqlCommand(findPatient, connection);
         using (NpgsqlDataReader personFromDataBase = person.ExecuteReader())
         {
             Survey p = new Survey();
             while (personFromDataBase.Read())
             {
                 //что делать с DateSpecified и Мисами?
                 if (personFromDataBase["survey_comment"] != DBNull.Value)
                     p.Comment = Convert.ToString(personFromDataBase["survey_comment"]);
                 TestReferralSurvey pers = new TestReferralSurvey(p);
                 pers.additional = TestAdditional.BuildAdditionalFromDataBaseData(idReferral);
                 if (personFromDataBase["id_survey_organ"] != DBNull.Value)
                     pers.surveyOrgan = TestCoding.BuildCodingFromDataBaseData(Convert.ToString(personFromDataBase["id_survey_organ"]));
                 if (personFromDataBase["id_survey_type"] != DBNull.Value)
                     pers.surveyType = TestCoding.BuildCodingFromDataBaseData(Convert.ToString(personFromDataBase["id_survey_type"]));
                 return pers;
             }
         }
     }
     return null;
 }
コード例 #21
0
ファイル: BagFilter.cs プロジェクト: TNOCS/csTouch
 /// <summary>
 /// Get all CBS neighbourhoods, specifically its name, boundary (in WKT), and center.
 /// </summary>
 public void Enhance(IEnumerable<LocationDescription> locationDescriptions)
 {
     using (var conn = new NpgsqlConnection(connectionString))
     {
         conn.Open();
         var streets = new List<string>();
         foreach (var locationDescription in locationDescriptions)
         {
             var query = string.Format(Query, locationDescription.RdBoundary);
             using (var command = new NpgsqlCommand(query, conn))
             {
                 try
                 {
                     using (var dr = command.ExecuteReader())
                     {
                         while (dr.Read())
                         {
                             streets.Add(dr["straat"].ToString());
                         }
                     }
                 }
                 catch (SystemException e)
                 {
                     Console.WriteLine(e.Message);
                 }
             }
             locationDescription.Features.Add("straten", string.Join(";", streets));
         }
     }
 }
コード例 #22
0
ファイル: DataReaderTests.cs プロジェクト: baondp/Npgsql
 public void RecordsAffected()
 {
     var command = new NpgsqlCommand("insert into data (field_int4) values (7); insert into data (field_int4) values (8)", Conn);
     using (var dr = command.ExecuteReader()) {
         Assert.AreEqual(2, dr.RecordsAffected);
     }
 }
コード例 #23
0
 public static List<PlanCommission> getListPlanCommission(String query)
 {
     NpgsqlConnection con = Connexion.Connection();
     try
     {
         List<PlanCommission> l = new List<PlanCommission>();
         NpgsqlCommand Lcmd = new NpgsqlCommand(query, con);
         NpgsqlDataReader lect = Lcmd.ExecuteReader();
         if (lect.HasRows)
         {
             while (lect.Read())
             {
                 PlanCommission a = new PlanCommission();
                 a.Id = Convert.ToInt64(lect["id"].ToString());
                 a.Nature = lect["nature_commission"].ToString();
                 a.Reference = lect["reference"].ToString();
                 a.Commissions = BLL.CommissionBll.Liste("select * from yvs_com_commission where plan = " + a.Id);
                 a.Update = true;
                 l.Add(a);
             }
             lect.Close();
         }
         return l;
     }
     catch (NpgsqlException e)
     {
         Messages.Exception(e);
         return null;
     }
     finally
     {
         Connexion.Deconnection(con);
     }
 }
コード例 #24
0
ファイル: NumericTypeTests.cs プロジェクト: ru-sh/npgsql
        public void Int32()
        {
            var cmd = new NpgsqlCommand("SELECT @p1, @p2, @p3", Conn);
            var p1 = new NpgsqlParameter("p1", NpgsqlDbType.Integer);
            var p2 = new NpgsqlParameter("p2", DbType.Int32);
            var p3 = new NpgsqlParameter { ParameterName = "p3", Value = 8 };
            Assert.That(p3.NpgsqlDbType, Is.EqualTo(NpgsqlDbType.Integer));
            Assert.That(p3.DbType, Is.EqualTo(DbType.Int32));
            cmd.Parameters.Add(p1);
            cmd.Parameters.Add(p2);
            cmd.Parameters.Add(p3);
            p1.Value = p2.Value = (long)8;
            var reader = cmd.ExecuteReader();
            reader.Read();

            for (var i = 0; i < cmd.Parameters.Count; i++)
            {
                Assert.That(reader.GetInt32(i),                 Is.EqualTo(8));
                Assert.That(reader.GetInt64(i),                 Is.EqualTo(8));
                Assert.That(reader.GetInt16(i),                 Is.EqualTo(8));
                Assert.That(reader.GetByte(i),                  Is.EqualTo(8));
                Assert.That(reader.GetFloat(i),                 Is.EqualTo(8.0f));
                Assert.That(reader.GetDouble(i),                Is.EqualTo(8.0d));
                Assert.That(reader.GetDecimal(i),               Is.EqualTo(8.0m));
                Assert.That(reader.GetValue(i),                 Is.EqualTo(8));
                Assert.That(reader.GetProviderSpecificValue(i), Is.EqualTo(8));
                Assert.That(reader.GetFieldType(i),             Is.EqualTo(typeof(int)));
                Assert.That(reader.GetDataTypeName(i),          Is.EqualTo("int4"));
            }

            reader.Dispose();
            cmd.Dispose();
        }
コード例 #25
0
        public List<OrganizationType> QueryAllOnOrganizationType()
        {
            try
            {
                this.OpenConn();
                string SQL = "SELECT * FROM Organization_Type";
                NpgsqlCommand command = new NpgsqlCommand(SQL, conn);
                NpgsqlDataReader dr = command.ExecuteReader();
                List<OrganizationType> orgTypes = new List<OrganizationType>();

                while (dr.Read())
                {
                    OrganizationType type = new OrganizationType();
                    type.Name = dr["name"].ToString();
                    type.Description = dr["description"].ToString();
                    orgTypes.Add(type);
                }
                this.CloseConn();
                return orgTypes;
            }
            catch (Exception ne)
            {
                Console.WriteLine("error on query table connecting to server, Error details {0}", ne.ToString());
                return null;
            }
        }
コード例 #26
0
ファイル: RemiseDao.cs プロジェクト: dowesw/GESTION_CAISSE
 public static List<Remise> getListRemise(String query)
 {
     NpgsqlConnection con = Connexion.Connection();
     try
     {
         List<Remise> l = new List<Remise>();
         NpgsqlCommand Lcmd = new NpgsqlCommand(query, con);
         NpgsqlDataReader lect = Lcmd.ExecuteReader();
         if (lect.HasRows)
         {
             while (lect.Read())
             {
                 Remise a = new Remise();
                 a.Id = Convert.ToInt64(lect["id"].ToString());
                 a.Reference = lect["reference"].ToString();
                 a.BaseRemise = lect["base_remise"].ToString();
                 a.Permanent = Convert.ToBoolean((lect["permanent"] != null) ? (!lect["permanent"].ToString().Trim().Equals("") ? lect["permanent"].ToString().Trim() : "false") : "false");
                 a.Grilles = BLL.GrilleRemiseBll.Liste("SELECT * FROM yvs_com_grille_remise WHERE remise =" + a.Id);
                 a.Update = true;
                 l.Add(a);
             }
             lect.Close();
         }
         return l;
     }
     catch (NpgsqlException e)
     {
         Messages.Exception(e);
         return null;
     }
     finally
     {
         Connexion.Deconnection(con);
     }
 }
コード例 #27
0
ファイル: Login.cs プロジェクト: felipegsa/us
        public void LogarUsuario(string email, string pass)
        {
            string strCom = "Select id_usuario, email_usuario , nm_usuario , senha_usuario from usuario where email_usuario = :email_usuario and senha_usuario = :senha_usuario";
            try
            {
                using (NpgsqlConnection conexao = ConnectionFactory.createConnection())
                {
                    Model.Aluno objAluno = new Model.Aluno();
                    NpgsqlCommand comm = new NpgsqlCommand(strCom, conexao);
                    comm.Parameters.AddWithValue("email_usuario", email);
                    comm.Parameters.AddWithValue("senha_usuario", pass);
                    NpgsqlDataReader dataReader = comm.ExecuteReader();

                    CarregarAluno(dataReader);
                    //carregarCursos
                    CursoDAL dalCurso = new CursoDAL();
                    List<Model.Curso> vListCurso = new List<Model.Curso>();
                    vListCurso = dalCurso.ObterCursoXAluno(Model.Session.Session.Aluno.Id);
                    Model.Session.Session.Aluno.CursoCadastrado = new List<Model.Curso>();
                    Model.Session.Session.Aluno.CursoCadastrado = vListCurso;
                }
            }
            catch (Exception ex)
            {
                //log
                throw new ExceptionDAL(ex.Message, ex);
            }
        }
コード例 #28
0
        public string markeratid()
        {
            //Skapar int nummer som innehåller en vald rad i dataGridView1.
            int nummer = dataGridView1.CurrentRow.Index;

            //Skapar strängen valtid.
            //Strängen innehåller information om spelare. Hämtar golfid från databasen, tabellen person.
            String valtid = "select golfid from person;";
            //Skapar ett nytt Npgsql kommando, command10.
            NpgsqlCommand command10 = new NpgsqlCommand(valtid, Huvudfönster.conn);
            //Skapar en Npgsql "DataReader", dr4. Samt utför kommando, command10.
            NpgsqlDataReader dr4 = command10.ExecuteReader();

            //Skapar strängen id.
            //Skapar int räknare och sätter denna till 0.
            string id = "";
            int räknare = 0;

            //Skapar en while-loop.
            while (dr4.Read())
            {
                //Gör en uträkning för golfid.
                if (räknare == nummer)
                {
                    id = dr4["golfid"].ToString();
                }
                räknare = räknare + 1;
            }

            //Stänger DataReader.
            dr4.Close();

            return id;
        }
コード例 #29
0
        /// <summary>
        /// This method reads users from database, looks for username match and checks
        /// if pass is correct for given username.
        /// </summary>
        /// <returns> Bool representing success or failure of user login</returns>
        public static bool Verify(string name, string pass)
        {
            using(NpgsqlConnection conn = Connect())
            {
                conn.Open();
                NpgsqlCommand command = new NpgsqlCommand("select name, pass from users order by id ASC", conn);
                NpgsqlDataReader table = command.ExecuteReader();

                List<Users> output = new List<Users>();
                foreach (IDataRecord row in table)
                {
                    if (name == (string)row["name"])
                    {
                        if(pass == (string)row["pass"])
                        {
                            // do something here to give authorization cookie?
                            // or if not here, then on client side?
                            return true;
                        }
                        else{
                            throw new System.ApplicationException("Name and pass do not match.");
                            // return false;
                        }
                    }
                }
            }
            return false;
        }
コード例 #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (SiteMaster.Rank == "2" && SiteMaster.LoggedIn)
            {
                // Specify connection options and open an connection
                NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;" +
                                        "Password=root;Database=project56;");
                conn.Open();

                // Define query
                NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM users", conn);

                // Execute query
                NpgsqlDataReader dr = cmd.ExecuteReader();

                //Get rows and place in ArrayList
                while (dr.Read())
                {
                    maillist.Add(dr[0]);
                    ranklist.Add(dr[2]);
                }

                // Close connection
                conn.Close();

                for(int i=0;i<maillist.Count;i++)
                {
                    maildrop.Items.Add(maillist[i].ToString()); //Add all emails to dropdown
                }
            }
        }