protected PostgresSqlDatabaseContext(DataAccessModel model, SqlDialect sqlDialect, SqlDataTypeProvider sqlDataTypeProvider, SqlQueryFormatterManager sqlQueryFormatterManager, PostgresSqlDatabaseContextInfo contextInfo) : base(model, sqlDialect, sqlDataTypeProvider, sqlQueryFormatterManager, contextInfo.DatabaseName, contextInfo) { this.SupportsPreparedTransactions = contextInfo.EnablePreparedTransactions; this.Host = contextInfo.ServerName; this.UserId = contextInfo.UserId; this.Password = contextInfo.Password; this.Port = contextInfo.Port; var connectionStringBuilder = new NpgsqlConnectionStringBuilder { Host = contextInfo.ServerName, Username = contextInfo.UserId, Password = contextInfo.Password, Port = contextInfo.Port, Pooling = contextInfo.Pooling, Enlist = false, MinPoolSize = contextInfo.MinPoolSize, MaxPoolSize = contextInfo.MaxPoolSize, KeepAlive = contextInfo.KeepAlive, ConnectionIdleLifetime = contextInfo.ConnectionIdleLifetime, ConvertInfinityDateTime = contextInfo.ConvertInfinityDateTime }; if (contextInfo.Timeout != null) { connectionStringBuilder.Timeout = contextInfo.Timeout.Value; } if (contextInfo.ConnectionTimeout.HasValue) { connectionStringBuilder.Timeout = contextInfo.ConnectionTimeout.Value; } if (contextInfo.ConnectionCommandTimeout.HasValue) { connectionStringBuilder.CommandTimeout = contextInfo.ConnectionCommandTimeout.Value; } connectionStringBuilder.Database = contextInfo.DatabaseName; this.ConnectionString = connectionStringBuilder.ToString(); connectionStringBuilder.Database = "postgres"; this.ServerConnectionString = connectionStringBuilder.ToString(); this.SchemaManager = new PostgresSqlDatabaseSchemaManager(this); }
public static void Initialize() { var connectionString = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; var connectionBuilder = new NpgsqlConnectionStringBuilder(connectionString); //connect to postgres database to create a new database var databaseName = connectionBuilder.Database; connectionBuilder.Database = "postgres"; connectionString = connectionBuilder.ToString(); using (var conn = new NpgsqlConnection(connectionString)) { conn.Open(); bool dbExists; using (var cmd = new NpgsqlCommand()) { cmd.CommandText = string.Format(@"SELECT TRUE FROM pg_database WHERE datname='{0}'", databaseName); cmd.Connection = conn; var result = cmd.ExecuteScalar(); dbExists = result != null && Convert.ToBoolean(result); } if (dbExists) { DoClean(conn); } else { DoCreate(conn, databaseName); } } }
// Zu Quell- und Zieldatenbank verbinden private void connectFischFaunaButton_Click(object sender, EventArgs e) { DatabaseConnection sourceCon = (DatabaseConnection)sourceDatabaseConnetions.SelectedValue; DatabaseConnection targetCon = (DatabaseConnection)targetDatabaseConnetions.SelectedValue; NpgsqlConnectionStringBuilder pgConStrBuilder = new NpgsqlConnectionStringBuilder(); pgConStrBuilder.Host = sourceCon.ServerAddress; pgConStrBuilder.UserName = sourceCon.UserName; pgConStrBuilder.Password = sourceCon.Password; pgConStrBuilder.Database = sourceCon.Database; MySqlConnectionStringBuilder mySqlConStrBuilder = new MySqlConnectionStringBuilder(); mySqlConStrBuilder.Server = targetCon.ServerAddress; mySqlConStrBuilder.UserID = targetCon.UserName; mySqlConStrBuilder.Password = targetCon.Password; mySqlConStrBuilder.Database = targetCon.Database; mySqlConStrBuilder.AllowZeroDateTime = true; _sourceCon = new NpgsqlConnection(pgConStrBuilder.ToString()); _targetCon = new MySqlConnection(mySqlConStrBuilder.ToString()); _mainLogic = new MainLogic(_sourceCon, _targetCon); _mainLogic.CheckForImportedFieldInMySql(); FillImportsCombobox(); FillImportUsersCombobox(); FillRecordQualityCombobox(); FillSourceTypeCombobox(); FillCountryCombobox(); PreSelectTestData(); groupBox2.Enabled = true; }
internal static bool TestConnectionString(string connectString) { //Connection should be fast var sb = new Npgsql.NpgsqlConnectionStringBuilder(connectString); sb.Timeout = 15; connectString = sb.ToString(); var valid = false; using (var conn = new NpgsqlConnection()) { try { conn.ConnectionString = connectString; conn.Open(); valid = true; } catch (Exception ex) { Log.Warning(ex.ToString()); valid = false; } finally { conn.Close(); } } return(valid); }
public static NpgsqlConnection CreateConnection() { NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder(GetConnectionString()); csb.Enlist = false; var connection = new NpgsqlConnection(csb.ToString()); connection.Open(); return connection; }
public void Bug1011001() { //[#1011001] Bug in NpgsqlConnectionStringBuilder affects on cache and connection pool var csb1 = new NpgsqlConnectionStringBuilder(@"Server=server;Port=5432;User Id=user;Password=passwor;Database=database;"); var cs1 = csb1.ToString(); var csb2 = new NpgsqlConnectionStringBuilder(cs1); var cs2 = csb2.ToString(); Assert.IsTrue(cs1 == cs2); }
public string ForceTestDB(string connectionString) { var cb = new NpgsqlConnectionStringBuilder(connectionString); if (!cb.Database.EndsWith("_test")) { cb.Database += "_test"; } return cb.ToString(); }
private static void CreateDatabase() { var cxBuilder = new NpgsqlConnectionStringBuilder(ConnectionString); var database = cxBuilder.Database; cxBuilder.Database = null; var db = new NpgsqlConnection(cxBuilder.ToString()); db.Execute($"DROP DATABASE IF EXISTS \"{database}\""); db.Execute($"CREATE DATABASE \"{database}\""); }
protected PostgresSqlDatabaseContext(DataAccessModel model, SqlDialect sqlDialect, SqlDataTypeProvider sqlDataTypeProvider, SqlQueryFormatterManager sqlQueryFormatterManager, PostgresSqlDatabaseContextInfo contextInfo) : base(model, sqlDialect, sqlDataTypeProvider, sqlQueryFormatterManager, contextInfo.DatabaseName, contextInfo) { this.Host = contextInfo.ServerName; this.UserId = contextInfo.UserId; this.Password = contextInfo.Password; this.Port = contextInfo.Port; var connectionStringBuilder = new NpgsqlConnectionStringBuilder { Host = contextInfo.ServerName, Username = contextInfo.UserId, Password = contextInfo.Password, Port = contextInfo.Port, Pooling = contextInfo.Pooling, Enlist = false, BackendTimeouts = contextInfo.BackendTimeouts, MinPoolSize = contextInfo.MinPoolSize, MaxPoolSize = contextInfo.MaxPoolSize }; if (contextInfo.ConnectionTimeout.HasValue) { connectionStringBuilder.Timeout = contextInfo.ConnectionTimeout.Value; } if (contextInfo.ConnectionCommandTimeout.HasValue) { connectionStringBuilder.CommandTimeout = contextInfo.ConnectionCommandTimeout.Value; } connectionStringBuilder.Database = contextInfo.DatabaseName; this.ConnectionString = connectionStringBuilder.ToString(); connectionStringBuilder.Database = "postgres"; this.ServerConnectionString = connectionStringBuilder.ToString(); this.SchemaManager = new PostgresSqlDatabaseSchemaManager(this); }
static void Main(string[] args) { var b = new NpgsqlConnectionStringBuilder() { Host = "milkyway", Port = 5433, Username = "******", Password = "******", Database = "db" }; using (DbConnection conn = new NpgsqlConnection(b.ToString())) { conn.Open(); var tables = new List<string>(); var all = conn.GetSchema("Tables"); foreach (DataRow r in all.Rows) { //table_catalog //table_schema //table_name //table_type var schema = r["table_schema"]; var table = r["table_name"]; var type = r["table_type"]; if ("kernel".Equals(schema.ToString())) tables.Add(table.ToString()); } foreach (var table in tables) { Console.WriteLine("Table: " + table); var tableSchema = conn.GetSchema("Columns", new string[] { null, null, table }); foreach (DataRow row in tableSchema.Rows) { Console.WriteLine("Column = {0}. Type = {1}. Default = {2}. Nullable = {3}. Text lenght = {4}. Numeric precision = {5}.", row["column_name"], row["data_type"], row["column_default"], row["is_nullable"], row["character_maximum_length"], row["numeric_precision"]); } } /*var cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = @"SELECT * FROM kernel.users;"; using (var reader = cmd.ExecuteReader()) while (reader.Read()) Console.WriteLine(string.Format("id = {0}, user = {1};", reader.GetString(0), reader.GetString(1))); */ } Console.ReadKey(); }
internal static string BuildConnectionString(bool integratedSecurity, string databaseName, string serverName, string userName, string password) { var connStr = new StringBuilder(); var sb = new Npgsql.NpgsqlConnectionStringBuilder(); sb.IntegratedSecurity = integratedSecurity; sb.Database = databaseName; sb.Host = serverName; if (!integratedSecurity) { sb.Username = userName; sb.Password = password; } return(sb.ToString()); }
public MainForm() { InitializeComponent(); RecordsProgressBar.Maximum = RecordsMax; _count = 0; _close = false; _threadsCounter = 0; DbConnectionStringBuilder connectionStringBuilder = new NpgsqlConnectionStringBuilder(); connectionStringBuilder.Add("Server", "localhost"); connectionStringBuilder.Add("Port", "5432"); connectionStringBuilder.Add("User Id", "postgres"); connectionStringBuilder.Add("Password", "1"); connectionStringBuilder.Add("Database", "project"); _dbConnectionString = connectionStringBuilder.ToString(); }
public DataManager() { Npgsql.NpgsqlConnectionStringBuilder ssb = new Npgsql.NpgsqlConnectionStringBuilder(); ssb.Host = "localhost"; ssb.Port = 5432; ssb.Username = "******"; ssb.Password = "******"; ssb.Database = "test_db"; ssb.CommandTimeout = 30; ssb.Pooling = true; ssb.MaxPoolSize = 20; ssb.MinPoolSize = 1; var cond = new Npgsql.NpgsqlConnection(ssb.ToString()); database = new Database(cond.ConnectionString); }
public DBService(ConnectionVO connVO,string HostURL) { try { NpgsqlConnectionStringBuilder nsb = new NpgsqlConnectionStringBuilder(); nsb.Host = HostURL; nsb.Port = 5432; nsb.SSL = false; nsb.IntegratedSecurity = false; nsb.UserName = "******"; nsb.Database = connVO.DataBaseName; nsb.Password = connVO.DBPassword; NpgConn = new NpgsqlConnection(nsb.ToString()); NpgConn.Open(); } catch (Exception ex) { throw ex; } }
static RequiresPostgresFactAttribute() { IsPostgresAvailable = new Lazy<bool>(() => { try { var builder = new NpgsqlConnectionStringBuilder(PostgresFixture.ConnectionString); builder.Timeout = 1000; using (var connection = new NpgsqlConnection(builder.ToString())) { connection.Open(); return connection.State == ConnectionState.Open; } } catch (Exception) { return false; } }); }
public PostgresSQLDBServicecs(ConnectionVO connVO) { try { this.myConnVO = connVO; NpgsqlConnectionStringBuilder nsb = new NpgsqlConnectionStringBuilder(); nsb.Host = connVO.HostURL; nsb.Port = 5432; nsb.SSL = false; nsb.IntegratedSecurity = false; nsb.UserName = connVO.DBID; nsb.Database = connVO.DataBaseName; nsb.Password = connVO.DBPassword; nsb.Pooling = false; NpgConn = new NpgsqlConnection(nsb.ToString()); NpgConn.Open(); } catch (Exception ex) { throw ex; } }
/*List<SpaceWar2006.GameSystem.GameServerInfo> infos = new List<SpaceWar2006.GameSystem.GameServerInfo>(); protected void Answer(NetIncomingMessage msg) { SpaceWar2006.GameSystem.GameServerInfo info; { string p = msg.ReadString(); info = new SpaceWar2006.GameSystem.GameServerInfo(p); infos.Add(info); } }*/ protected void Page_Load(object sender, EventArgs e) { /*ServerFinder finder = new ServerFinder(new ServerFinder.AnswerDelegate(Answer), false, true); GridView1.AutoGenerateColumns = true; for (int i = 0; i < 5; ++i) { finder.Tick(0.5f); Thread.Sleep(500); } GridView1.DataSource = infos; GridView1.DataBind();*/ NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder (); builder.Host = "localhost"; builder.Password = ""; builder.Pooling = false; builder.UserName = "******"; builder.Database = "game"; NpgsqlConnection c=new NpgsqlConnection(builder.ToString()); c.Open(); NpgsqlCommand cmd = c.CreateCommand (); cmd.CommandText = @"SELECT s2.id,s2.name,s2.host,s2.port,i2.time,i2.map,i2.numplayers,i2.maxplayers FROM (SELECT s.id AS id,MAX(i.time) AS maxtime FROM gameserver s LEFT JOIN gameinfo i ON s.id=i.gameserver_id GROUP BY s.id) AS times LEFT JOIN gameserver s2 ON times.id=s2.id LEFT JOIN gameinfo i2 ON times.id=i2.gameserver_id AND times.maxtime=i2.time"; //NpgsqlDataReader r = cmd.ExecuteReader(); NpgsqlDataAdapter a=new NpgsqlDataAdapter(cmd); DataTable dt=new DataTable(); a.Fill(dt); GridView1.DataSource=dt; GridView1.DataBind(); }
public PostgreSQLDatabase() { Name = "Postgre"; CollectionName = "table1"; Category = "SQL"; Description = "PostgreSQL + Npgsql 2.0.13.91 .NET Data Provider"; Website = "http://www.postgresql.org/"; Color = System.Drawing.Color.FromArgb(0, 148, 196); Requirements = new string[] { "MySql.Data.dll" }; NpgsqlConnectionStringBuilder cs = new NpgsqlConnectionStringBuilder(); cs.Host = "localhost"; cs.Port = 5432; cs.UserName = "******"; cs.Password = "******"; cs.CommandTimeout = 0; cs.ConnectionLifeTime = 0; ConnectionString = cs.ToString(); }
public void Bug184RollbackFailsOnAbortedTransaction() { NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder(ConnectionString); csb.CommandTimeout = 100000; using (NpgsqlConnection connTimeoutChanged = new NpgsqlConnection(csb.ToString())) { connTimeoutChanged.Open(); using (var t = connTimeoutChanged.BeginTransaction()) { try { var command = new NpgsqlCommand("select count(*) from dta", connTimeoutChanged); command.Transaction = t; Object result = command.ExecuteScalar(); } catch (Exception) { t.Rollback(); } } } }
internal NpgsqlConnection CreateAndOpenConnection() { var connectionStringBuilder = new NpgsqlConnectionStringBuilder(_connectionString) { Enlist = false //Npgsql is not fully compatible with TransactionScope yet. }; var connection = new NpgsqlConnection(connectionStringBuilder.ToString()); connection.Open(); return connection; }
/// <summary> /// Gets an connection instance based on current ConnectionString value /// </summary> /// <returns>Connection instance</returns> protected NpgsqlConnection GetConnection(string connectionString) { NpgsqlConnectionStringBuilder mySQLConnectionStringBuilder = new NpgsqlConnectionStringBuilder(connectionString); return new NpgsqlConnection(mySQLConnectionStringBuilder.ToString()); }
private void btnCreateDatabase_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtConnectionString.Text)) { MessageBox.Show("Empty connection string"); return; } try { if (rbSQLServer.Checked) { SqlConnection.ClearAllPools(); var cb = new SqlConnectionStringBuilder(txtConnectionString.Text); var dbname = cb.InitialCatalog; cb.InitialCatalog = "master"; using (var db = new SqlConnection(cb.ToString())) { db.Open(); var cmd = new SqlCommand(string.Format("CREATE DATABASE [{0}]", dbname), db); cmd.ExecuteNonQuery(); } } else { NpgsqlConnection.ClearAllPools(); var cb = new NpgsqlConnectionStringBuilder(txtConnectionString.Text); var dbname = cb.Database; cb.Database = "postgres"; using (var db = new NpgsqlConnection(cb.ToString())) { db.Open(); var cmd = new NpgsqlCommand(string.Format("CREATE DATABASE \"{0}\";", dbname), db); cmd.ExecuteNonQuery(); } cb.Database = dbname; using (var db = new NpgsqlConnection(cb.ToString())) { db.Open(); var cmd = new NpgsqlCommand(@"CREATE OR REPLACE FUNCTION uuid_generate_v4() RETURNS uuid AS '$libdir/uuid-ossp', 'uuid_generate_v4' VOLATILE STRICT LANGUAGE C;", db); cmd.ExecuteNonQuery(); } } MessageBox.Show("Success", "Database creation", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("Error connecting to database:\n" + ex.Message, "Database creation", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void Main(string[] args) { NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder (); builder.Host = "localhost"; builder.Password = ""; builder.Pooling = false; builder.UserName = "******"; builder.Database = "game"; int i = Array.IndexOf<string> (args, "--password"); if (i != -1) { builder.Password = args[i + 1]; } i = Array.IndexOf<string> (args, "--host"); if (i != -1) { builder.Host = args[i + 1]; } i = Array.IndexOf<string> (args, "--database"); if (i != -1) { builder.Database = args[i + 1]; } i = Array.IndexOf<string> (args, "--username"); if (i != -1) { builder.UserName = args[i + 1]; } string cstring = builder.ToString (); System.Console.WriteLine (cstring); while (true) { try { infos.Clear(); using (NpgsqlConnection c = new NpgsqlConnection(cstring)) { c.Open(); NpgsqlCommand cmd = c.CreateCommand(); cmd.CommandText = "SELECT * FROM gameserver"; NpgsqlDataReader r = cmd.ExecuteReader(); List<ServerFinder.Server> list = new List<ServerFinder.Server>(); while (r.Read()) { string host = (string)r["host"]; int port = (int)r["port"]; ServerFinder.Server s = new ServerFinder.Server(host, port); list.Add(s); } ServerFinder finder = new ServerFinder(new ServerFinder.AnswerDelegate(Answer), false, list); while (true) { for (i = 0; i < 10; ++i) { finder.Tick(0.1f); Thread.Sleep(100); } foreach (KeyValuePair<string, SpaceWar2006.GameSystem.GameServerInfo> info in infos) { string host = info.Key.Split(':')[0]; int port = int.Parse(info.Key.Split(':')[1]); string map = info.Value.Map; int numplayers = info.Value.NumPlayers; int maxplayers = info.Value.MaxPlayers; string sql = string.Format(@"INSERT INTO gameinfo(time,map,numplayers,maxplayers,gameserver_id) VALUES (NOW(),'{2}',{3},{4},(SELECT id FROM gameserver WHERE host='{0}' AND port={1}));", host, port, map, numplayers, maxplayers); System.Console.WriteLine(sql); cmd = c.CreateCommand(); cmd.CommandText = sql; cmd.ExecuteNonQuery(); } infos.Clear(); } } } catch (NpgsqlException e) { System.Console.WriteLine(e.GetType().ToString()); System.Console.WriteLine(e.StackTrace); System.Console.WriteLine(e.Message); } Thread.Sleep(1000); } }
/// <summary> /// Create a database /// </summary> /// <param name="dbInfo">DbDriverInfo</param> public void CreatePhysicalDatabase(DbDriverInfo dbInfo) { NpgsqlConnectionStringBuilder masterBuilder = new NpgsqlConnectionStringBuilder(dbInfo.DBCnnStringBuilder.ToString()); NpgsqlConnectionStringBuilder tempBuilder = new NpgsqlConnectionStringBuilder(dbInfo.DBCnnStringBuilder.ToString()); //tempBuilder = dbInfo.DBCnnStringBuilder as MySqlConnectionStringBuilder; //The "test" database is installed by default with MySQL. System needs to login to this database to create a new database. tempBuilder.Database = "information_schema"; NpgsqlConnection masterConnection = new NpgsqlConnection(tempBuilder.ToString()); try { NpgsqlCommand command = masterConnection.CreateCommand(); if(dbInfo.DBName != null) { command.CommandText = "create database " + dbInfo.DBName + ";"; } masterConnection.Open(); //Logger.Log(command.CommandText); command.ExecuteNonQuery(); //reset database to new database for correct storage of meta tables tempBuilder.Database = dbInfo.DBName; } catch (Exception ex) { throw new System.ApplicationException("Could not create new MySQL Database", ex);//(Epi.SharedStrings.CAN_NOT_CREATE_NEW_MYSQL, ex); } finally { masterConnection.Close(); } }
/// <summary> /// Creates initial connection string from user-supplied database, server, user, and password input. /// </summary> /// <param name="database">Data store.</param> /// <param name="server">Server location of database.</param> /// <param name="user">User account login Id.</param> /// <param name="password">User login password.</param> /// <returns></returns> public string BuildDefaultConnectionString(string database, string server, int port, string user, string password) { NpgsqlConnectionStringBuilder mySQLConnBuild = new NpgsqlConnectionStringBuilder(); //mySQLConnBuild.PersistSecurityInfo = false; mySQLConnBuild.Database = database; mySQLConnBuild.Host = server; mySQLConnBuild.Port = port; mySQLConnBuild.UserName = user; mySQLConnBuild.Password = password; return mySQLConnBuild.ToString(); }
public String GetConnectionStringNoDatabase() { switch (DatabaseTypeEnum) { case DatabaseTypeEnum.mysql: { var builder = new MySqlConnectionStringBuilder { Server = Server, UserID = Username, Password = Password, }; if (Port != null) { builder.Port = (uint) Port; } return builder.ToString(); } case DatabaseTypeEnum.postgresql:{ var builder = new NpgsqlConnectionStringBuilder { Host = Server, UserName = Username, Password = Password, }; if (Port != null) { builder.Port = Port.Value; } return builder.ToString(); } } throw new ArgumentException(); }
private NpgsqlConnection CreateConnection(ConnSet connSet) { if (string.IsNullOrEmpty(ConnectionString)) { NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder { Host = connSet.txtDbIP.Text, UserName = connSet.txtUserName.Text, Password = connSet.txtPassword.Text, Database = connSet.txtDbName.Text }; ConnectionString = builder.ToString(); } return new NpgsqlConnection(ConnectionString); }
private void Connect() { lock (_oSyncRoot) { if (null != _cTransaction) return; try { if (null != _cConnection && ConnectionState.Closed != _cConnection.State) _cConnection.Close(); } catch { } Npgsql.NpgsqlConnectionStringBuilder sConnectionString = new NpgsqlConnectionStringBuilder(); sConnectionString.Add("Server", _cCredentials.sServer); sConnectionString.Add("Port", _cCredentials.nPort); sConnectionString.Add("User Id", _cCredentials.sUser); sConnectionString.Add("Password", _cCredentials.sPassword); sConnectionString.Add("Database", _cCredentials.sDatabase); sConnectionString.Add("Timeout", _cCredentials.nTimeout); sConnectionString.Add("CommandTimeout", _cCredentials.nTimeout); _sLastQuery = sConnectionString.ToString().Replace("\\;", ";") + ";Encoding=Unicode;"; _cConnection = new NpgsqlConnection(_sLastQuery); _sLastQuery = "Connect to server: " + _sLastQuery; _cConnection.Open(); if (null != _cCredentials.sRole && 0 < _cCredentials.sRole.Length) (new NpgsqlCommand("SET ROLE " + _cCredentials.sRole, _cConnection)).ExecuteNonQuery(); if(Preferences.ByteaOutput.server != Preferences.eByteaOutput) (new NpgsqlCommand("SET bytea_output TO " + Preferences.eByteaOutput, _cConnection)).ExecuteNonQuery(); } }