Exemple #1
0
        public static void LoadDatabase()
        {
            Logging.Write("Connecting to database");

            try
            {
                var connectionString = new MySqlConnectionStringBuilder
                {
                    ConnectionTimeout     = 10,
                    Database              = GetConfig().Data["db.name"],
                    DefaultCommandTimeout = 30,
                    Logging             = false,
                    MaximumPoolSize     = uint.Parse(GetConfig().Data["db.pool.maxsize"]),
                    MinimumPoolSize     = uint.Parse(GetConfig().Data["db.pool.minsize"]),
                    Password            = GetConfig().Data["db.password"],
                    Pooling             = true,
                    Port                = uint.Parse(GetConfig().Data["db.port"]),
                    Server              = GetConfig().Data["db.hostname"],
                    UserID              = GetConfig().Data["db.username"],
                    AllowZeroDateTime   = true,
                    ConvertZeroDateTime = true,
                };

                DatabaseManager = new DatabaseManager(connectionString.ToString());

                Logging.WriteSimpleLine(" - Completed!");
            }
            catch (Exception Error)
            {
                Logging.WriteSimpleLine(" - Incomplete!");
                Logging.LogError(Error.ToString());
                Logging.WriteLine("Failed to connect to MySQL server!", ConsoleColor.Red);
                Logging.WriteLine("Press any key to shut down ...", ConsoleColor.Red);
                Console.ReadKey(true);
                Environment.Exit(1);
                return;
            }
        }
Exemple #2
0
        public frmmalzemeekrani()
        {
            InitializeComponent();
            MySqlConnectionStringBuilder bag = new MySqlConnectionStringBuilder();

            bag.Server   = "localhost";
            bag.UserID   = "root";
            bag.Password = "******";
            bag.Database = "dbhastanebts";
            baglanti     = new MySqlConnection(bag.ToString());

            //malzeme tablosu select,insert
            MySqlCommand cmd_malzeme_sel = new MySqlCommand("select id,malzemeadi,malzemecinsi,malzemeadedi,malzemeaciklama,malzemegiristarihi from malzeme", baglanti);

            da_malzeme = new MySqlDataAdapter();
            da_malzeme.SelectCommand = cmd_malzeme_sel;
            MySqlCommand cmd_malzeme_ins = new MySqlCommand("insert into malzeme(malzemeadi,malzemecinsi,malzemeadedi,malzemegiristarihi,malzemeaciklama) values(@malzemeadi,@malzemecinsi,@malzemeadedi,@malzemegiristarihi,@malzemeaciklama)", baglanti);

            cmd_malzeme_ins.Parameters.Add("@malzemeadi", MySqlDbType.VarChar, 45, "malzemeadi");
            cmd_malzeme_ins.Parameters.Add("@malzemecinsi", MySqlDbType.VarChar, 45, "malzemecinsi");
            cmd_malzeme_ins.Parameters.Add("@malzemeadedi", MySqlDbType.Int32, 11, "malzemeadedi");
            cmd_malzeme_ins.Parameters.Add("@malzemegiristarihi", MySqlDbType.VarChar, 45, "malzemegiristarihi");
            cmd_malzeme_ins.Parameters.Add("@malzemeaciklama", MySqlDbType.VarChar, 45, "malzemeaciklama");

            da_malzeme.InsertCommand = cmd_malzeme_ins;
            malzemegetir();



            //

            da_ustbirim = new MySqlDataAdapter();

            // ustbirim tablosu select,insert
            MySqlCommand cmd_ustbirim_sel = new MySqlCommand("select id,malzemeadi,malzemecinsi,malzemeadedi,malzemegiristarihi");

            da_ustbirim.SelectCommand = cmd_ustbirim_sel;
        }
Exemple #3
0
        /// <summary>
        /// static constructor to determine the state of the environment and set defaults
        /// </summary>
        static CurrentEnvironment()
        {
            // Not on cloud foundry filling in the blanks.
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(INSTANCE_GUID_ENV_VARIABLE_NAME)))
            {
                Environment.SetEnvironmentVariable(BOUND_SERVICES_ENV_VARIABLE_NAME, "{}");
                Environment.SetEnvironmentVariable(PORT_ENV_VARIABLE_NAME, NOT_ON_CLOUD_FOUNDRY_MESSAGE);
                Environment.SetEnvironmentVariable(INSTANCE_GUID_ENV_VARIABLE_NAME, NOT_ON_CLOUD_FOUNDRY_MESSAGE);
                Environment.SetEnvironmentVariable(INSTANCE_INDEX_ENV_VARIABLE_NAME, NOT_ON_CLOUD_FOUNDRY_MESSAGE);
            }

            // check to see if DB is bound, if so...what type
            // sql server first
            if (BoundServices.GetValue("mssql-dev") != null) // sql server
            {
                DbEngine          = DatabaseEngine.SqlServer;
                _connectionString = BoundServices["mssql-dev"][0]["credentials"]["connectionString"].ToString();
            }
            else if (BoundServices.GetValue("p-mysql") != null)
            {
                DbEngine = DatabaseEngine.MySql;;
                MySqlConnectionStringBuilder csbuilder = new MySqlConnectionStringBuilder();
                csbuilder.Add("server", BoundServices["p-mysql"][0]["credentials"]["hostname"].ToString());
                csbuilder.Add("port", BoundServices["p-mysql"][0]["credentials"]["port"].ToString());
                csbuilder.Add("uid", BoundServices["p-mysql"][0]["credentials"]["username"].ToString());
                csbuilder.Add("pwd", BoundServices["p-mysql"][0]["credentials"]["password"].ToString());
                csbuilder.Add("database", BoundServices["p-mysql"][0]["credentials"]["name"].ToString());
                _connectionString = csbuilder.ToString();
            }
            else
            {
                DbEngine = DatabaseEngine.None;
            }

            Console.WriteLine("BUILD SERVICE INFO...");
            Console.WriteLine(_connectionString);
            Console.WriteLine("BUILD SERVICE INFO...");
        }
        public static string HelloWorld()
        {
            try
            {
                MySqlConnectionStringBuilder connectionBuilder = new MySqlConnectionStringBuilder
                {
                    Server   = "localhost",
                    Port     = 3307,
                    UserID   = "root", //francois
                    Password = "",     //root
                    Database = "confposte"
                };
                string hello = null;

                using (MySqlConnection connection = new MySqlConnection(connectionBuilder.ToString()))
                {
                    connection.Open();

                    using (MySqlCommand command = new MySqlCommand("SELECT libelle FROM hello;", connection))
                    {
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                hello = reader.GetString("libelle");
                            }
                        }
                    }
                }

                return(hello);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                throw e;
            }
        }
Exemple #5
0
        private void buttonAtualizar_Click(object sender, EventArgs e)
        {
            if (ValidarCampos())
            {
                return;
            }

            MySqlConnectionStringBuilder conexaoBD = new MySqlConnectionStringBuilder();

            conexaoBD.Server   = "localhost";
            conexaoBD.Database = "locadora_carros";
            conexaoBD.UserID   = "root";
            conexaoBD.Password = "";
            MySqlConnection realizaConexacoBD = new MySqlConnection(conexaoBD.ToString());

            try
            {
                realizaConexacoBD.Open();                                      //Abre a conexão com o banco

                MySqlCommand comandoMySql = realizaConexacoBD.CreateCommand(); //Crio um comando SQL
                comandoMySql.CommandText = "UPDATE clientes SET nome = '" + textboxNome.Text + "', " +
                                           "local_retirada = '" + comboboxLocal.Text + "', " +
                                           "data_retirada = '" + dateTimePickerRetirada.Value.ToString("yyyy-MM-dd") + "', " +
                                           "data_entrega = '" + dateTimePickerDevolucao.Value.ToString("yyyy-MM-dd") + "', " +
                                           "modelo_veiculo = '" + comboboxVeiculo.Text + "' WHERE id = " + textboxId.Text + "";
                comandoMySql.ExecuteNonQuery();

                realizaConexacoBD.Close(); // Fecho a conexão com o banco
                MessageBox.Show("Atualizado com sucesso");
                atualizarGrid();
                limparCampos();
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Não foi possivel abrir a conexão! ");
                Console.WriteLine(ex.Message);
            }
        }
Exemple #6
0
        public String GetConnectionString()
        {
            switch (DatabaseTypeEnum)
            {
            case DatabaseTypeEnum.mysql:
            {
                var builder = new MySqlConnectionStringBuilder
                {
                    Server   = Server,
                    UserID   = Username,
                    Password = Password,
                    Database = Database,
                };
                if (Port != null)
                {
                    builder.Port = (uint)Port.Value;
                }
                return(builder.ToString());
            }

            case DatabaseTypeEnum.postgresql:
            {
                var builder = new NpgsqlConnectionStringBuilder
                {
                    Host     = Server,
                    UserName = Username,
                    Password = Password,
                    Database = Database,
                };
                if (Port != null)
                {
                    builder.Port = Port.Value;
                }
                return(builder.ToString());
            }
            }
            throw new ArgumentException();
        }
Exemple #7
0
        private void buttonHapusBaju_Click(object sender, EventArgs e)
        {
            if (textBoxIdBaju.Text != "")
            {
                MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
                builder.Server   = SERVER;
                builder.Database = DATABASE;
                builder.UserID   = UID;
                builder.Password = PASSWORD;

                String connString = builder.ToString();

                dbConn = new MySqlConnection(connString);

                FormPeringatan frmP = new FormPeringatan(this);
                frmP.isiLabel("Apakah anda yakin?");
                DialogResult result = frmP.ShowDialog();
                if (result == DialogResult.OK)
                {
                    String query = string.Format("DELETE  from pesan_baju where Id IN ('" + textBoxIdBaju.Text + "')");

                    MySqlCommand cmd = new MySqlCommand(query, dbConn);
                    dbConn.Open();
                    cmd.ExecuteNonQuery();
                    dbConn.Close();
                    MessageBox.Show("Anda berhasil menghapus");
                    loadBaju();
                }
                else if (result == DialogResult.Cancel)
                {
                    MessageBox.Show("hapus dibatalkan");
                }
            }
            else
            {
                MessageBox.Show("Data tidak boleh kosong");
            }
        }
Exemple #8
0
        /// <summary>
        /// Acepta un objeto tipo conexión y crea una cadena de conexión bien formada
        /// de tipo MySQL
        /// </summary>
        /// <param name="usarSSL">Si la conexión debe usar SSL.</param>
        /// <returns>Cadena de conexión válida MySQL</returns>
        private string ObtenerCadenaConexionMySQL(bool usarSSL)
        {
            MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();

            builder.Server = Direccion;
            if (BaseDatos != null)
            {
                builder.Database = BaseDatos;
            }
            else
            {
                builder.Database = "";
            }

            builder.UserID   = UsuarioConexion;
            builder.Password = ContraseniaConexion;
            if (!usarSSL)
            {
                builder.SslMode = MySqlSslMode.None;
            }

            return(builder.ToString());
        }
Exemple #9
0
        protected void ProcessOutstandingEmails(CancellationToken stoppingToken)
        {
            MySqlConnectionStringBuilder csBuilder = new MySqlConnectionStringBuilder()
            {
                Server   = _mantisDbConfig.Host,
                Port     = _mantisDbConfig.Port,
                Database = _mantisDbConfig.Database,
                UserID   = _mantisDbConfig.Username,
                Password = _mantisDbConfig.Password
            };

            using (var oDB = new MySqlConnection(csBuilder.ToString()))
            {
                oDB.Open();

                var sentIdList = SendEmailsFromDatabase(stoppingToken, oDB);

                if (sentIdList.Count > 0)
                {
                    RemoveSentEmails(stoppingToken, oDB, sentIdList);
                }
            }
        }
Exemple #10
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         var conexion = new MySqlConnectionStringBuilder
         {
             Server              = "localhost",
             UserID              = "root",
             Password            = "******",
             Database            = "prueba",
             Port                = 3306,
             PersistSecurityInfo = true,
             SslMode             = none
         };
         var con = new MySqlConnection(conexion.ToString());
         con.Open();
         MessageBox.Show("Conectado a la base de datos");
     }
     catch (Exception)
     {
         MessageBox.Show("NO ESTA Conectado a la base de datos");
     }
 }
Exemple #11
0
      public DBHandler(string server, MySqlConnectionProtocol protocol, uint timeout = 20, uint poolsize = 40, uint lifetime = 3600)
      {
          if (lifetime != 0 && lifetime < timeout)
          {
              throw new ArgumentException("lifetime < timeout");
          }
          var builder = new MySqlConnectionStringBuilder()
          {
              Server                = server,
              ConnectionProtocol    = protocol,
              Database              = "twiten",
              SslMode               = MySqlSslMode.None, //にゃーん
              UserID                = "twigaten",
              Password              = "",
              MinimumPoolSize       = 1,
              MaximumPoolSize       = poolsize, //デフォルトは100
              ConnectionLifeTime    = lifetime,
              CharacterSet          = "utf8mb4",
              DefaultCommandTimeout = timeout      //デフォルトは20(秒
          };

          ConnectionStr = builder.ToString();
      }
Exemple #12
0
 public static void createConnection(string user_id, string password, string name_database, int port)
 {
     if (_connection == null)
     {
         // setup new connection
         MySqlConnectionStringBuilder b = new MySqlConnectionStringBuilder();
         my_lock     = new Object();
         b.Server    = "127.0.0.1";
         b.UserID    = user_id;
         b.Password  = password;
         b.Database  = name_database;
         b.SslMode   = MySqlSslMode.None;
         b.Port      = (uint)port;
         _connection = new MySqlConnection(b.ToString());
         try
         {
             _connection.Open();
         } catch
         {
             throw new Exception("Cannot connect to MySQL");
         }
     }
 }
        private void sil()
        {
            string bag;
            MySqlConnectionStringBuilder build = new MySqlConnectionStringBuilder();

            build.UserID   = "root";
            build.Password = "";
            build.Database = "newdatabase";
            build.Server   = "localhost";
            bag            = build.ToString();
            baglanti       = new MySqlConnection(bag);
            string           sql     = "DELETE FROM kullanici WHERE idkullanici=" + textBox1.Text + ";";
            DataTable        dt      = new DataTable();
            MySqlDataAdapter adapter = new MySqlDataAdapter();
            MySqlCommand     command = new MySqlCommand();

            command.CommandText   = sql;
            command.Connection    = baglanti;
            adapter.SelectCommand = command;
            //   baglanti.Open();
            adapter.Fill(dt);
            dataGridView1.DataSource = dt;
        }
Exemple #14
0
        public MySqlConnection GetConexion()
        {
            MySqlConnection conexion = null;

            try
            {
                MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
                builder.Server   = "localhost";
                builder.Port     = 3306;
                builder.UserID   = "root";
                builder.Password = "";
                builder.Database = "cine";

                //Asigna y abre la conexión
                conexion = new MySqlConnection(builder.ToString());
                conexion.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error en la conexión: " + ex.Message);
            }
            return(conexion);
        }
Exemple #15
0
        //private const string conStr = "";

        public static IDbConnection OpenConnection()
        {
            var cBuilder = new MySqlConnectionStringBuilder();

            cBuilder.Server   = "localhost";
            cBuilder.UserID   = "root";
            cBuilder.Password = "******";
            cBuilder.Database = "classicmodels";
            var conStr = cBuilder.ToString();

            var connection = new MySqlConnection(conStr);

            connection.Open();
            return(connection);

            System.Data.SqlClient.SqlConnectionStringBuilder builder =
                new System.Data.SqlClient.SqlConnectionStringBuilder();

            builder.DataSource     = "";
            builder.UserID         = "";
            builder.Password       = "";
            builder.InitialCatalog = "";
        }
Exemple #16
0
        private void buttonSalvar_Click(object sender, EventArgs e)
        {
            MySqlConnectionStringBuilder conexaoBD = conexaoBanco();
            MySqlConnection realizaConexacoBD      = new MySqlConnection(conexaoBD.ToString()); try

            {
                realizaConexacoBD.Open();

                MySqlCommand comandoMySql = realizaConexacoBD.CreateCommand();
                comandoMySql.CommandText = "INSERT INTO filme (nomeFilme,generoFilme,anoFilme) " +
                                           "VALUES('" + textBoxNome.Text + "', '" + textBoxGenero.Text + "', " + Convert.ToInt16(textBoxAno.Text) + ")";
                comandoMySql.ExecuteNonQuery();

                realizaConexacoBD.Close();
                MessageBox.Show("Inserido!");
                limparCampos();
                atualizarGrid();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemple #17
0
        private DBConnection()
        {
            MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder()
            {
                Server   = SERVER,
                UserID   = UID,
                Password = PASSWORD,
                Database = DATABASE,
                SslMode  = MySqlSslMode.None
            };

            String connString = builder.ToString();

            dbConn = new MySqlConnection(connString);
            Application.ApplicationExit += (sender, args) =>
            {
                if (dbConn != null)
                {
                    dbConn.Dispose();
                    dbConn = null;
                }
            };
        }
Exemple #18
0
        /// <summary>
        /// Publiczna funkcja pozwalająca dodać płatność do zamówienia kontrahenta
        /// </summary>
        public void DodajPlatnoscDoPortalgames()
        {
            MySqlConnectionStringBuilder portalgamesconn = Utils.PortalGamesConnSring;

            using (MySqlConnection conn = new MySqlConnection(portalgamesconn.ToString()))
            {
                conn.Open();
                string sqlCommand = "INSERT INTO `order_pay_history`(order_id, add_date, pay_date, user_id, customer_id, price_brutto) VALUES(@orderId, @addDate, @payDate, @userId, @customerId, @priceBrutto);";
                using (var cmd = conn.CreateCommand())
                {
                    cmd.Parameters.AddWithValue("orderId", Zamowienie.IdZamowienia);
                    cmd.Parameters.AddWithValue("addDate", DateTime.Now.Date);
                    cmd.Parameters.AddWithValue("payDate", DateTime.Now.Date);
                    cmd.Parameters.AddWithValue("userId", 3);
                    cmd.Parameters.AddWithValue("customerId", 0);
                    cmd.Parameters.AddWithValue("priceBrutto", Zamowienie.KwotaDoZaplaty);
                    cmd.CommandText = sqlCommand;

                    cmd.ExecuteNonQuery();
                }
                conn.Close();
            }
        }
 public void InsertBuilding()
 {
     if (String.IsNullOrWhiteSpace(tbAddressBuilding.Text) == false && String.IsNullOrWhiteSpace(tbNameBuilding.Text) == false && numNoF.Value > 0)
     {
         MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder
         {
             Server       = "localhost",
             Port         = 3306,
             UserID       = "skill09-95",
             Password     = "******",
             Database     = "skills_it_95",
             CharacterSet = "utf8"
         };
         MySqlConnection conn = new MySqlConnection(sb.ToString());
         MySqlCommand    cmd  = new MySqlCommand("INSERT INTO buildings (name, num_of_floors, address) VALUES (@name, @num_of_floors, @address)", conn);
         cmd.Parameters.AddWithValue("@name", tbNameBuilding.Text);
         cmd.Parameters.AddWithValue("@num_of_floors", numNoF.Value);
         cmd.Parameters.AddWithValue("@address", tbAddressBuilding.Text);
         cmd.Connection.Open();
         cmd.ExecuteNonQuery();
         cmd.Connection.Close();
     }
 }
        private void btnSalvar_Click(object sender, EventArgs e)
        {
            MySqlConnectionStringBuilder conexaoBD = conexaoBanco();
            MySqlConnection realizaConexaoBD       = new MySqlConnection(conexaoBD.ToString());

            try
            {
                realizaConexaoBD.Open();

                MySqlCommand comandoMySql = realizaConexaoBD.CreateCommand();
                comandoMySql.CommandText = "INSERT INTO carros (idCarro,ModeloCarro, MarcaCarro, AnoCarro, CorCarro) VALUES ('" + txtID.Text + "','" + txtModelo.Text + "', '" + txtMarca.Text + "', " + txtAno.Text + ", '" + txtCor.Text + "')";
                comandoMySql.ExecuteNonQuery();

                realizaConexaoBD.Close();
                MessageBox.Show("Inserido com sucesso!");
                atualizarGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Não foi possível abrir a conexão!");
                Console.WriteLine(ex.Message);
            }
        }
        private void connect()
        {
            MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder();

            sb.Server       = "localhost";
            sb.UserID       = "root";
            sb.Password     = "";
            sb.Database     = "cs_harcosok";
            sb.CharacterSet = "utf8";

            conn = new MySqlConnection(sb.ToString());

            try
            {
                conn.Open();
                sql = conn.CreateCommand();
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                Environment.Exit(0);
            }
        }
        public MySqlConnection GetMySqlConnection()
        {
            MySqlConnectionStringBuilder connectionString = new MySqlConnectionStringBuilder
            {
                Server   = m_hostname,
                Port     = 3306,
                UserID   = m_user,
                Password = m_password,
                Database = m_database,
            };
            MySqlConnection connection = new MySqlConnection(connectionString.ToString());

            try
            {
                connection.Open();
                connection.Close();
            }
            catch
            {
                return(null);
            }
            return(connection);
        }
Exemple #23
0
        public static void EstablishConnection()
        {
            try
            {
                MySqlConnectionStringBuilder stringBuilder = new MySqlConnectionStringBuilder();
                stringBuilder.Server   = "127.0.0.1";
                stringBuilder.UserID   = "root";
                stringBuilder.Password = "******";
                stringBuilder.Database = "csgo";
                stringBuilder.SslMode  = MySqlSslMode.None;
                stringBuilder.AllowPublicKeyRetrieval = true;
                stringBuilder.AutoEnlist         = true;
                stringBuilder.AllowUserVariables = true;
                connection = new MySqlConnection(stringBuilder.ToString());

                // Get the logger
                // MessageBox.Show("Database connection successful", "Connection", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception e)
            {
                MessageBox.Show("Connection Failed!");
            }
        }
 static PCFEnvironment()
 {
     if (BoundServices.GetValue("p-mysql") != null)
     {
         MySqlConnectionStringBuilder csbuilder = new MySqlConnectionStringBuilder();
         csbuilder.Add("server", BoundServices["p-mysql"][0]["credentials"]["hostname"].ToString());
         csbuilder.Add("port", BoundServices["p-mysql"][0]["credentials"]["port"].ToString());
         csbuilder.Add("uid", BoundServices["p-mysql"][0]["credentials"]["username"].ToString());
         csbuilder.Add("pwd", BoundServices["p-mysql"][0]["credentials"]["password"].ToString());
         csbuilder.Add("database", BoundServices["p-mysql"][0]["credentials"]["name"].ToString());
         _connectionString = csbuilder.ToString();
     }
     else if (BoundServices.GetValue("p.mysql") != null)
     {
         MySqlConnectionStringBuilder csbuilder = new MySqlConnectionStringBuilder();
         csbuilder.Add("server", BoundServices["p.mysql"][0]["credentials"]["hostname"].ToString());
         csbuilder.Add("port", BoundServices["p.mysql"][0]["credentials"]["port"].ToString());
         csbuilder.Add("uid", BoundServices["p.mysql"][0]["credentials"]["username"].ToString());
         csbuilder.Add("pwd", BoundServices["p.mysql"][0]["credentials"]["password"].ToString());
         csbuilder.Add("database", BoundServices["p.mysql"][0]["credentials"]["name"].ToString());
         _connectionString = csbuilder.ToString();
     }
 }
        private static void Connect(out MySqlConnection con)
        {
            try
            {
                MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
                builder.Server   = SERVER;
                builder.UserID   = USERNAME;
                builder.Password = PASSWORD;
                builder.Database = DATABASE;
                builder.SslMode  = MySqlSslMode.None;

                String connString = builder.ToString();
                builder = null;

                Console.WriteLine(connString);
                con = new MySqlConnection(connString);
            }
            catch (Exception ex)
            {
                Console.WriteLine("DBConnection | Caught an exception while executing Connect() : " + ex);
                con = null;
            }
        }
Exemple #26
0
 public static bool EstableceConexion(string sUsuario, string sPassword, string sServer, string sDatabase)
 {
     try
     {
         MySqlConnectionStringBuilder cnx = new MySqlConnectionStringBuilder();
         cnx.Server   = sServer;
         cnx.UserID   = sUsuario;
         cnx.Password = sPassword;
         cnx.Database = sDatabase;
         cnx.SslMode  = MySqlSslMode.None;
         connection   = new MySqlConnection(cnx.ToString());
         if (connection.State == ConnectionState.Open)
         {
             connection.Close();
         }
         connection.Open();
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
        public static void connectMySQL()
        {
            MySqlConnectionStringBuilder _stringConnection = new MySqlConnectionStringBuilder
            {
                Server   = "localhost",
                Database = "database",
                UserID   = "root",
                Password = "******",
                Port     = 3306
            };

            //  string connectionString = "SERVER=sql12.freemysqlhosting.net;PORT=3306;DATABASE=sql12232054;UID=sql12232054;PWD=L2shZZrK4X";
            mysqlConnection = new MySqlConnection(_stringConnection.ToString());
            try
            {
                mysqlConnection.Open();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                MessageBox.Show("Can't connect MySQL");
            }
        }
    public void conectar()
    {
        MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();

        builder.Server   = "mysql5013.smarterasp.net";
        builder.UserID   = "a131fe_bd";
        builder.Password = "******";
        builder.Database = "db_a131fe_bd";
        MySqlConnection con = new MySqlConnection(builder.ToString());
        MySqlCommand    cmd = con.CreateCommand();

        try
        {
            con.Open();
        }
        catch (Exception)
        {
        }
        finally
        {
            con.Close();
        }
    }
        /// <summary>
        ///
        /// </summary>
        /// <param name="dbOptions"></param>
        /// <param name="options"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="loginInfo"></param>
        public MySqlDbContextOptions(DbOptions dbOptions, DbModuleOptions options, ILoggerFactory loggerFactory, ILoginInfo loginInfo) : base(dbOptions, options, new MySqlAdapter(dbOptions, options), loggerFactory, loginInfo)
        {
            if (options.ConnectionString.IsNull())
            {
                Check.NotNull(dbOptions.Server, nameof(dbOptions.Server), "数据库服务器地址不能为空");
                Check.NotNull(dbOptions.UserId, nameof(dbOptions.UserId), "数据库用户名不能为空");
                Check.NotNull(dbOptions.Password, nameof(dbOptions.Password), "数据库密码不能为空");

                options.Version = dbOptions.Version;
                var connStrBuilder = new MySqlConnectionStringBuilder
                {
                    Server             = DbOptions.Server,
                    Port               = DbOptions.Port > 0 ? (uint)DbOptions.Port : 3306,
                    Database           = options.Database,
                    UserID             = DbOptions.UserId,
                    Password           = DbOptions.Password,
                    AllowUserVariables = true,
                    CharacterSet       = "utf8",
                    SslMode            = MySqlSslMode.None
                };
                options.ConnectionString = connStrBuilder.ToString();
            }
        }
Exemple #30
0
        async void initDb()
        {
            //Create a new connectionstring
            MySqlConnectionStringBuilder _sb = new MySqlConnectionStringBuilder();

            _sb.Server   = sqlServer;
            _sb.Database = sqlDatabase;
            _sb.UserID   = sqlUserID;
            _sb.Password = sqlPassword;

            string _cs = _sb.ToString();

            //Open new sql connection
            sqlConnection = new MySqlConnection(_cs);
            await sqlConnection.OpenAsync();

            //Just checking if the connection is valid
            sqlState = sqlConnection.State;
            ConsoleLog.Write(ConsoleState.Warning, $"Database connection -> {sqlState.ToString()}");

            //Mandatory to close connection after each call.
            await sqlConnection.CloseAsync();
        }