当前位置: 首页>>代码示例>>C#>>正文


C# NpgsqlConnection.Open方法代码示例

本文整理汇总了C#中Npgsql.NpgsqlConnection.Open方法的典型用法代码示例。如果您正苦于以下问题:C# NpgsqlConnection.Open方法的具体用法?C# NpgsqlConnection.Open怎么用?C# NpgsqlConnection.Open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Npgsql.NpgsqlConnection的用法示例。


在下文中一共展示了NpgsqlConnection.Open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Button1_Click

 protected void Button1_Click(object sender, EventArgs e)
 {
     string checks;
     string checkw;
     string id_sali = DropDownList1.SelectedItem.ToString();
     string id_wyp = DropDownList2.SelectedItem.ToString();
     NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=projekt;Database=projekt;");
     conn.Open();
     NpgsqlCommand check1 = new NpgsqlCommand("select id_sali from wyp_sali where id_sali = '" + id_sali + "'", conn);
     NpgsqlCommand check2 = new NpgsqlCommand("select id_wyp from wyp_sali where id_sali = '" + id_sali + "'and id_wyp = '" + id_wyp + "'", conn);
     checks = (String)check1.ExecuteScalar();
     checkw = (String)check2.ExecuteScalar();
     if (checks == id_sali && checkw == id_wyp)
     {
         Label2.Text = "";
         Label3.Text = "Wyposażenie jest już przypisane do sali!";
     }
     else if (checkw != id_wyp)
     {
         NpgsqlCommand add = new NpgsqlCommand("insert into wyp_sali values ('" + id_wyp + "', '" + id_sali + "')", conn);
         add.ExecuteScalar();
         conn.Close();
         Label2.Text = "Dodano wyposażenie do sali!";
         Label3.Text = "";
     }
 }
开发者ID:grzesiekkulpa,项目名称:WWW_Rezerwacja_Sal,代码行数:26,代码来源:wyp_sali.aspx.cs

示例2: Bug1011241_DiscardAll

        public void Bug1011241_DiscardAll()
        {
            var connection = new NpgsqlConnection(ConnectionString + ";SearchPath=public");
            connection.Open();

            if (connection.PostgreSqlVersion < new Version(8, 3, 0)
                || new NpgsqlConnectionStringBuilder(ConnectionString).Protocol == ProtocolVersion.Version2)
            {
                connection.Close();
                return;
            }

            using (var command = connection.CreateCommand())
            {
                command.CommandText = "SHOW SEARCH_PATH";
                Assert.AreEqual("public", command.ExecuteScalar());

                command.CommandText = "SET SEARCH_PATH = \"$user\"";
                command.ExecuteNonQuery();
                command.CommandText = "SHOW SEARCH_PATH";
                Assert.AreEqual("\"$user\"", command.ExecuteScalar());
            }
            connection.Close();

            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = "SHOW SEARCH_PATH";
                Assert.AreEqual("public", command.ExecuteScalar());
            }
            connection.Close();
        }
开发者ID:kristofen,项目名称:Npgsql,代码行数:32,代码来源:ConnectionTests.cs

示例3: CreateUser_Click

        protected void CreateUser_Click(object sender, EventArgs e)
        {
            //ArrayList for emails
            ArrayList maillist = new ArrayList();

            // 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;");

            //Open connection
            conn.Open();

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

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

            //Get rows and place in ArrayList
            while (dr.Read())
            {
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    maillist.Add(dr[i]);
                }
            }

            // Close connection
            conn.Close();

            //Check if email in TextBox equals one of the existing accounts
            for (int i = 0; i < maillist.Count; i++)
            {
                if (maillist[i].Equals(Email.Text))
                {
                    EmailUnique = false;
                    MessageBox.Show(Page, "Dit emailadres is al geregistreerd!");
                    break;
                }
            }

            if (EmailUnique)
            {
                //Insert Email and Password from TextBoxes
                conn.Open();

                NpgsqlCommand cmd1 = new NpgsqlCommand("INSERT INTO users(email, password, rank) VALUES (:email, :pw, 0)", conn);
                cmd1.Parameters.Add(new NpgsqlParameter("email", Email.Text));
                cmd1.Parameters.Add(new NpgsqlParameter("pw", Password.Text));

                cmd1.ExecuteNonQuery();

                conn.Close();

                MessageBox.Show(Page, "Uw account is geregistreerd!");

            }
        }
开发者ID:TheLeftovers,项目名称:Input,代码行数:58,代码来源:Register.aspx.cs

示例4: OpenDBConnection

    /// <summary>
    /// Gets an open connection to the DB. Can be called any number of times.
    /// </summary>
    /// <param name="connectionString">
    /// The connection String.
    /// </param>
    /// <returns>
    /// The <see cref="NpgsqlConnection"/>.
    /// </returns>
    public static NpgsqlConnection OpenDBConnection(string connectionString)
    {
        // create the connection
        var connection = new NpgsqlConnection(connectionString);
             connection.Notification += new NotificationEventHandler(Connection_InfoMessage);
             connection.Open();
        if (connection.State == ConnectionState.Broken)
        {
            connection.Close();
            connection.Open();
        }

        return connection;
    }
开发者ID:vzrus,项目名称:VZF,代码行数:23,代码来源:DbConnManager.cs

示例5: pgsql_API

		/// <summary>
		/// Default constructor.
		/// </summary>
		/// <param name="intitString"></param>
		public pgsql_API(string intitString)
		{
			// connectionstring=
			string[] parameters = intitString.Replace("\r\n","\n").Split('\n');
			foreach(string param in parameters){
				if(param.ToLower().IndexOf("connectionstring=") > -1){
					m_ConStr = param.Substring(17);
				}
			}
         
            SqlConnectionStringBuilder b = new SqlConnectionStringBuilder(m_ConStr);
            string database = b.InitialCatalog;
            b.InitialCatalog = "";              
            using(NpgsqlConnection con = new NpgsqlConnection(b.ToString().ToLower().Replace("data source","server"))){                    
                con.Open();

                // See if database exists
                try{
                    con.ChangeDatabase(database);
                }
                catch{
                    // Database don't exist, try to create it

                    try{
                        con.Close();
                        con.ConnectionString = b.ToString().ToLower().Replace("data source","server");
                        con.Open();


                        NpgsqlCommand cmd = new NpgsqlCommand();
                        cmd.Connection = con;
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = "create database \"" + database + "\"";
                        cmd.ExecuteNonQuery();
                        con.ChangeDatabase(database);

                        // Create tables
                        cmd.CommandText = ResManager.GetText("tables.sql",System.Text.Encoding.Default);
                        cmd.ExecuteNonQuery();

                        // Create procedures
                        cmd.CommandText = ResManager.GetText("procedures.sql",System.Text.Encoding.Default);
                        cmd.ExecuteNonQuery();
                    }
                    catch{
                        throw new Exception("Database '" + database + "' doesn''t exist ! Create failed, specified user doesn't have enough permisssions to create database ! Create database manually.");
                    }                    
                }
            }
		}
开发者ID:dioptre,项目名称:nkd,代码行数:54,代码来源:pgsql_API.cs

示例6: Get

        // 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;
        }
开发者ID:fiit-pdt,项目名称:assignment-gis-mstrbak,代码行数:27,代码来源:ValuesController.cs

示例7: Incluir

 public void Incluir(Model_Vo_MovimentacaoEstoque pMovimentacaoEstoque)
 {
     SqlConnection cn = new SqlConnection();
     try
     {
         cn.ConnectionString = Academia.Model.Dao.Dados.Model_Dao_Dados.getStringDeConexao();
         //command
         SqlCommand cmd = new SqlCommand();
         cmd.Connection = cn;
         cmd.CommandText = "insert into movimentacaoestoque(datahora,idclientesolicitante,idproduto,idreservaorigem,quantidade,valorunitario,valortotal,tipodemovimento) values (@datahora,@idclientesolicitante,@idproduto,@idreservaorigem,@quantidade,@valorunitario,@valortotal,@tipodemovimento);";
         cmd.Parameters.AddWithValue("@datahora", Dados.Model_Dao_Dados.ConverterDataToStr(pMovimentacaoEstoque.DataHora, false));
         cmd.Parameters.AddWithValue("@idclientesolicitante", pMovimentacaoEstoque.IdClienteSolicitante);
         cmd.Parameters.AddWithValue("@idproduto", pMovimentacaoEstoque.IdProduto);
         cmd.Parameters.AddWithValue("@idreservaorigem", pMovimentacaoEstoque.IdReservaOrigem);
         cmd.Parameters.AddWithValue("@quantidade", pMovimentacaoEstoque.Quantidade);
         cmd.Parameters.AddWithValue("@valorunitario", pMovimentacaoEstoque.ValorUnitario);
         cmd.Parameters.AddWithValue("@valortotal", pMovimentacaoEstoque.ValorTotal);
         cmd.Parameters.AddWithValue("@tipodemovimento", pMovimentacaoEstoque.TipoDeMovimento.ToString());
         cn.Open();
         pMovimentacaoEstoque.Id = Convert.ToInt32(cmd.ExecuteScalar());
     }
     catch (SqlException ex)
     {
         throw new Exception("Servidor SQL Erro:" + ex.Number);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
     finally
     {
         cn.Close();
     }
 }
开发者ID:PablusVinii,项目名称:techgyn,代码行数:34,代码来源:Model_Dao_MovimentacaoEstoque.cs

示例8: Initialise

        /// <summary>
        /// Initialises the estatedata class.
        /// </summary>
        /// <param name="connectionString">connectionString.</param>
        public void Initialise(string connectionString)
        {
            if (!string.IsNullOrEmpty(connectionString))
            {
                m_connectionString = connectionString;
                _Database = new PGSQLManager(connectionString);
            }

            //Migration settings
            using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
            {
                conn.Open();
                Migration m = new Migration(conn, GetType().Assembly, "EstateStore");
                m.Update();
            }

            //Interesting way to get parameters! Maybe implement that also with other types
            Type t = typeof(EstateSettings);
            _Fields = t.GetFields(BindingFlags.NonPublic |
                                  BindingFlags.Instance |
                                  BindingFlags.DeclaredOnly);

            foreach (FieldInfo f in _Fields)
            {
                if (f.Name.Substring(0, 2) == "m_")
                    _FieldMap[f.Name.Substring(2)] = f;
            }
        }
开发者ID:BogusCurry,项目名称:arribasim-dev,代码行数:32,代码来源:PGSQLEstateData.cs

示例9: Run

        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();
                            }
                        }
                    }
                }
            }
        }
开发者ID:ekospinach,项目名称:kawaldesa,代码行数:27,代码来源:Program.cs

示例10: PostgreSQLDBManager

        private PostgreSQLDBManager()
        {
            _connection = new NpgsqlConnection(Configuration.Settings("PostgreSQLDBConnectionString",
                "User ID=postgres;Password=Passw0rd;Host=localhost;Port=5432;Database=postgres;Pooling=true;"));
            try
            {
                _connection.Open();
            }
            catch (Exception exception)
            {
                Log.Error(ExceptionHelper.FormatStackTrace("Connect to PostgreSQL failed.",exception));
                throw new RuntimeBinderException("Connect to Database Failed",exception);
            }

            var cmd = new NpgsqlCommand("select count(*) from content", _connection);
            var count = Convert.ToInt32(cmd.ExecuteScalar());
            if (count > 0)
                return;
            var rootId = Configuration.Settings("Root", "42c5eb51-0e1c-4de1-976d-733bde24220a");
            CreateSubItem(rootId, "Folder", "Data");
            CreateSubItem(rootId, "Folder", "UI");
            CreateSubItem(rootId, "Folder", "Translation");
            CreateSubItem(rootId, "Folder", "Project");
            CreateSubItem(rootId, "Folder", "Result");

            CreateSubItem("", "Project", "Root", rootId);
        }
开发者ID:bperreault,项目名称:autox,代码行数:27,代码来源:PostgreSQLDBManager.cs

示例11: Initialize

        public IDocumentStore Initialize(Action<MartenRegistry> register = null)
        {
            var builder = new NpgsqlConnectionStringBuilder(_targetConnectionString);
            var targetDatabaseName = builder.Database;

            using (var connection = new NpgsqlConnection(_masterConnectionString))
            {
                connection.Open();
                var existsCommand = connection.CreateCommand();
                existsCommand.CommandText = "select (count(*) > 0)::boolean as exists from pg_database where datname=:0";
                existsCommand.Parameters.Add(new NpgsqlParameter("0", targetDatabaseName));
                var exists = (bool)existsCommand.ExecuteScalar();
                if (!exists)
                {
                    var createCommand = connection.CreateCommand();
                    createCommand.CommandText = string.Format("CREATE DATABASE \"{0}\"", targetDatabaseName);
                    createCommand.ExecuteNonQuery();
                }
            }
            var store = DocumentStore.For(cfg =>
            {
                cfg.Connection(_targetConnectionString);
                cfg.AutoCreateSchemaObjects = true;
                cfg.Schema.For<Commit>()
                    .Searchable(x => x.StreamId)
                    .Searchable(x => x.StreamVersion);
                if (register != null)
                {
                    register(cfg.Schema);
                }
            });
            return store;
        }
开发者ID:jeffdoolittle,项目名称:Marten.Domain,代码行数:33,代码来源:Initializer.cs

示例12: getXml

 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 "";
 }
开发者ID:systemvetenskap,项目名称:OG,代码行数:25,代码来源:clsRightOrNot.cs

示例13: canHandIn

        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";
        }
开发者ID:systemvetenskap,项目名称:OG,代码行数:32,代码来源:clsRightOrNot.cs

示例14: Page_Load

        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
                }
            }
        }
开发者ID:TheLeftovers,项目名称:Input,代码行数:31,代码来源:UserManagement.aspx.cs

示例15: CreateConnection

        public static bool CreateConnection(ConnectionParams connectionParams, out NpgsqlConnection createdConnection)
        {
            bool result = false;
            string connstring = "";
            createdConnection = null;

            try
            {
                connstring = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};",
                                               connectionParams.Server, connectionParams.Port, connectionParams.Username, connectionParams.Password, connectionParams.Database);

                createdConnection = new NpgsqlConnection(connstring);

                if(connectionParams.OpenImmidiately)
                    createdConnection.Open();

                _allConnections.Add(createdConnection);
            }
            catch (Exception exc)
            {
                if (createdConnection != null && createdConnection.State == System.Data.ConnectionState.Open)
                    createdConnection.Close();

                createdConnection = null;
            }

            return result;
        }
开发者ID:Civa,项目名称:Zenith,代码行数:28,代码来源:ConnectionPool.cs


注:本文中的Npgsql.NpgsqlConnection.Open方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。