Ejemplo n.º 1
0
 /// <summary>
 /// Autor: Haroldo Arias
 /// Descripcion: Función que permite ejecutar un query dentro de la base de datos.
 /// </summary>
 /// <param name="query">
 /// Variable String que recibe el query a ejecutar.
 /// </param>
 /// <param name="db_base">
 /// Nombre de la base de datos en donde se correra el query
 /// </param>
 /// <returns>
 ///     Retornará true si el query fue ejecutado o false si fuera lo contrario.
 /// </returns>
 public bool execQuery(string query, string db_base)
 {
     try
     {
         openConexionMySQL();
         mysqlcon.ChangeDatabase(db_base);
         MySqlCommand com = new MySqlCommand();
         com.Connection  = mysqlcon;
         com.CommandType = CommandType.Text;
         com.CommandText = query;
         int resultado = com.ExecuteNonQuery();
         closeConexionMySQL();
         if (resultado > 0)
         {
             return(true);
         }
         return(false);
     }
     catch (Exception ex)
     {
         closeConexionMySQL();
         Console.Write(ex.Message);
         return(false);
     }
 }
Ejemplo n.º 2
0
        public void ChangeDatabaseNull()
        {
            var csb = AppConfig.CreateConnectionStringBuilder();

            using var connection = new MySqlConnection(csb.ConnectionString);
            Assert.Throws <ArgumentException>(() => connection.ChangeDatabase(null));
            Assert.Throws <ArgumentException>(() => connection.ChangeDatabase(""));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 该方法用于删除数据库中的格式设置信息
        /// </summary>
        /// <param name="formatname"></param>
        public void DeleteFormat(string formatname, string tablename)
        {
            string str_sql = $"delete from {tablename} where geshimingcheng='{formatname}'";

            mysql.ChangeDatabase("qianhai");
            MySqlCommand mycmd = new MySqlCommand(str_sql, mysql);

            mycmd.ExecuteNonQuery();
        }
Ejemplo n.º 4
0
 private void Select(string sqlselect, DataGridView d1)
 {
     try
     {
         if (conn.State == ConnectionState.Open)
         {
             conn.Close();
         }
         conn.Open();
         if (comboBox1.SelectedItem != null)
         {
             conn.ChangeDatabase(comboBox1.SelectedItem.ToString());
             data = new DataTable();
             da   = new MySqlDataAdapter(sqlselect, conn);
             da.Fill(data);
             if (d1.DataSource != null)
             {
                 d1.DataSource = null;
             }
             d1.DataSource = data;
         }
         else
         {
             MessageBox.Show("数据库不能为空");
         }
         conn.Close();
     }
     catch (MySqlException ex)
     {
         MessageBox.Show("Error: " + ex);
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// テーブルを作成するメソッド
        /// </summary>
        /// <param name="tableName">Createするテーブル名</param>
        /// <param name="columm">Createするカラム</param>
        /// <param name="primaryKey">設定するPRIMARY KEY</param>
        public void createTable(string tableName, string columm, string primaryKey)
        {
            bool connectBool = Connector.Connect("root", "root");

            if (connectBool)
            {
                conn.ChangeDatabase("felica");
            }
            string commandStr;

            if (primaryKey.Trim() != "")
            {
                commandStr = "CREATE TABLE " + tableName + "(" + columm + "," + "PRIMARY KEY(" + primaryKey + "));";
            }
            else
            {
                commandStr = "CREATE TABLE " + tableName + "(" + columm + ");";
            }
            MySqlCommand command = new MySqlCommand(commandStr, conn);

            try
            {
                command.ExecuteNonQuery();
                MessageBox.Show("Create Table Success!!");
            }
            catch (Exception ex)
            {
#if DEBUG
                MessageBox.Show(ex.Message);
#endif
            }
        }
Ejemplo n.º 6
0
        public bool TestMySqlConnection(string ServerName, string Database)
        {
            Server = ServerName;
            DBname = Database;
            if (!MakeMySQLconnection())
            {
                return(false);
            }

            try
            {
                if (DBname == "")
                {
                    throw new Exception("Database Name is empty!!");
                }
                oConn.ChangeDatabase(DBname);
            }
            catch (Exception e3)
            {
                txtStatus.Text = "Error connecting to database!!";
                MessageBox.Show("Error connecting to database: " + e3.Message, "ERROR");
                return(false);
            }

            //---- validate tables exist
            MySqlCommand oCmd = oConn.CreateCommand();

            oCmd.CommandType = CommandType.Text;
            try
            {
                MySqlDataAdapter oDA    = new MySqlDataAdapter(oCmd);
                DataTable        oTable = new DataTable();
                oCmd.CommandText = "select count(*) from fcc_element_descriptions";
                oDA.Fill(oTable);
                oTable.Clear();
                oCmd.CommandText = "select count(*) from fcc_exam_questions";
                oDA.Fill(oTable);
                oTable.Clear();
                oTable.Dispose();
                oDA.Dispose();
            }
            catch (Exception e4)
            {
                txtStatus.Text = "Error connecting to DB tables!!";
                MessageBox.Show("Error connecting to DB tables: " + e4.Message, "ERROR");
                return(false);
            }
            return(true);
        }
        DataTable FillClients(string proc, string filter, string id, string inTypes = null)
        {
            var    dtProcResult = new DataTable();
            string db           = String.Empty;

            try {
                if (MyCn.State != ConnectionState.Open)
                {
                    MyCn.Open();
                }
                db = MyCn.Database;
                MyCn.ChangeDatabase("reports");
                MyCmd.Connection   = MyCn;
                MyDA.SelectCommand = MyCmd;
                MyCmd.Parameters.Clear();
                MyCmd.Parameters.AddWithValue("inFilter", filter);
                MyCmd.Parameters["inFilter"].Direction = ParameterDirection.Input;
                if (id == String.Empty)
                {
                    MyCmd.Parameters.AddWithValue("inID", DBNull.Value);
                }
                else
                {
                    MyCmd.Parameters.AddWithValue("inID", Convert.ToInt64(id));
                }
                MyCmd.Parameters["inID"].Direction = ParameterDirection.Input;
                if (String.IsNullOrEmpty(inTypes))
                {
                    MyCmd.Parameters.AddWithValue("inTypes", -1);
                }
                else
                {
                    MyCmd.Parameters.AddWithValue("inTypes", inTypes);
                }
                MyCmd.Parameters["inTypes"].Direction = ParameterDirection.Input;
                MyCmd.CommandText = proc;
                MyCmd.CommandType = CommandType.StoredProcedure;
                MyDA.Fill(dtProcResult);
            }
            finally {
                if (db != String.Empty)
                {
                    MyCn.ChangeDatabase(db);
                }
                MyCmd.CommandType = CommandType.Text;
                MyCn.Close();
            }
            return(dtProcResult);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// execute a query
 /// </summary>
 /// <param name="queryString">The command to execute</param>
 public override void executeQuery(string queryString)
 {
     try {
         if (queryString.IndexOf("CREATE DATABASE") != -1)
         {
             conn.ChangeDatabase(ServerSettings.GetSetting("MySQL-DBName"));
         }
         MySqlCommand cmd = new MySqlCommand(queryString, conn);
         cmd.ExecuteNonQuery();
     }
     catch (Exception e)
     {
         Logger.LogError(e);
     }
 }
Ejemplo n.º 9
0
        private void databaseList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            MySqlDataReader reader = null;

            conn.ChangeDatabase(databaseList.SelectedItem.ToString());

            MySqlCommand cmd = new MySqlCommand("SHOW TABLES", conn);

            try
            {
                reader = cmd.ExecuteReader();
                tables.Items.Clear();
                while (reader.Read())
                {
                    tables.Items.Add(reader.GetString(0));
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Failed to populate table list: " + ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Ejemplo n.º 10
0
        //Отдельный метод для обновления DataGrid таблицы в редакторе
        public static void UpdateDataGrid()
        {
            using (var conn = new MySqlConnection(ConnectionString()))
            {
                //Открываем соединение
                conn.Open();
                conn.ChangeDatabase(Settings.Default.dbName);

                //Отправка запроса на обновление списка изданий из БД
                var newDataAdapter =
                    new MySqlDataAdapter(
                        "SELECT id,publication,is_magazine,date,issue_number,file_path FROM " +
                        Settings.Default.dbTableName, conn);

                var newDataSet = new DataSet();
                newDataAdapter.Fill(newDataSet, "dbBinding");
                //Заполняем таблицу в редакторе
                MWin.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                            (ThreadStart) delegate
                {
                    MWin.DbDataGrid.DataContext = newDataSet;
                    //Обновим информацию о файлах для поиска
                    Initialize.UpdateFilesDescriptions();
                });
            }
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            Console.WriteLine("Connect Clicked");
            string connetionString = null;


            connetionString = "server=localhost;port=3306;database=library;uid=tcowern;pwd=honda750;";
            MySqlConnection connect = new MySqlConnection(connetionString);

            try
            {
                connect.Open();
                Console.WriteLine("Connection Open ! ");

                Console.WriteLine("Server Version: " + connect.ServerVersion + "\nDatabase: " + connect.Database);
                string name = connect.Database;

                connect.ChangeDatabase("test");

                Console.WriteLine(("ServerVersion: " + connect.ServerVersion + "\nDatabase: " + connect.Database));
                connect.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Can not open connection ! ");
                Console.WriteLine(ex);
            }
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            MySqlConnection conn = new MySqlConnection();

            //Allg. Aufbau der Zeichenfolge für Verbindung
            //server=[servername];uid=[username];pwd=[password]
            //hier gilt: Username ist root und es gibt kein Passwort, Verbunden wird mit localhost
            String connString = "server=localhost;uid=root";

            conn.ConnectionString = connString;

            conn.Open();

            if (conn.State == System.Data.ConnectionState.Open)
            {
                Console.WriteLine("Verbindung aufgebaut");
            }
            else
            {
                Console.WriteLine("Verbindung konnte nicht hergestellt werden");
                return;
            }

            //Wechseln der Datenbank
            conn.ChangeDatabase("blumenladen");

            //Abfrage, wie viele Einträge in Tabelle verkauf vorhanden sind
            MySqlCommand comm = new MySqlCommand("select count(*) from verkauf", conn);

            Console.WriteLine("select count(*) from verkauf, gibt einen Wert von " + comm.ExecuteScalar() + " zurück");
            conn.Close();

            Console.ReadLine();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Créer et configure la base de donnée <code>dbName</code>
        /// </summary>
        /// <param name="dbconn">Objet de connexion à la base de données</param>
        /// <param name="dbName">Nom de la base de données à créer</param>
        /// <returns></returns>
        public static void SetupDB(MySqlConnection dbconn, string dbName)
        {
            // On essaie de créer la base de données
            try
            {
                // Créer la base de données vide
                MySqlCommand cmd = new MySqlCommand("CREATE DATABASE " + dbName, dbconn);
                dbconn.Open();
                cmd.ExecuteNonQuery();

                // Définie la connexion sur la nouvelle base de données créée précédemment
                dbconn.ChangeDatabase(dbName);

                // Lecture du script en ressources
                Stream       propertiesFile = Assembly.GetExecutingAssembly().GetManifestResourceStream("ProjectManagerCoreLib.data.projectmanager.sql");
                StreamReader reader         = new StreamReader(propertiesFile);
                string       content        = reader.ReadToEnd();

                // Préparation et execution du script
                MySqlScript script = new MySqlScript(dbconn, content);
                script.Error             += new MySqlScriptErrorEventHandler(script_Error);
                script.ScriptCompleted   += new EventHandler(script_ScriptCompleted);
                script.StatementExecuted += new MySqlStatementExecutedEventHandler(script_StatementExecuted);

                script.Execute();
                dbconn.Close();

                connectionString = string.Format("server={0};user={1};pwd={2};database={3}", dbSettings.GetDatabaseServer(), dbSettings.GetUser(), dbSettings.GetPassword(), dbSettings.GetDatabaseName());
                dbConnection     = new MySqlConnection(connectionString);
            }
            // On capture les éventuelle exceptions/erreurs
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 14
0
        override protected void LoadColumnsFromDatabase(string database)
        {
            // In MySQL all required information is inside the INFORMATION_SCHEMA Database
            client.ChangeDatabase("INFORMATION_SCHEMA");

            // Use a list to store the data in Memory and bulk insert it
            List <Columns> list = new List <Columns>();

            using (MySqlCommand command = client.CreateCommand())
            {
                command.CommandText = "SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @databaseName";
                command.Parameters.AddWithValue("@databaseName", database);

                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        list.Add(new Columns {
                            DatabaseName = database, Schema = "", TableName = reader.GetString(0), ColumnName = reader.GetString(1), DataType = reader.GetString(2)
                        });
                    }
                }
            }

            // Now that all fetched rows are in our list, lets add them in bulk to the SQLite database
            db.Columns.AddRange(list);
        }
Ejemplo n.º 15
0
 internal void Initialize(string ConnString)
 {
     connection = new MySqlConnection(ConnString);
     connection.Open();
     connection.ChangeDatabase(Databasing.DatabaseName);
     transaction = connection.BeginTransaction();
 }
Ejemplo n.º 16
0
        public QueryResult Query(string database, string sql)
        {
            MySqlConnection mySqlConnection = innerConnection();

            mySqlConnection.ChangeDatabase(database);
            return(mySqlConnection.Query(sql));
        }
Ejemplo n.º 17
0
        public List <string> GetAllTab(string db)
        {
            List <string> result = new List <string>();

            try
            {
                //查出所有的表名
                conn.Open();
                conn.ChangeDatabase(db);
                cmd.CommandText = string.Format("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{0}'", db);
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    result.Add(reader.GetString(0));
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            return(result);
        }
Ejemplo n.º 18
0
        private void databaseList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            MySqlDataReader reader = null;

            conn.ChangeDatabase(databaseList.SelectedItem.ToString());

            MySqlCommand cmd = new MySqlCommand("SHOW TABLES", conn);

            try {
                reader = cmd.ExecuteReader();
                tables.Items.Clear();
                while (reader.Read())
                {
                    tables.Items.Add(reader.GetString(0));
                }
            } catch (MySqlException ex) {
                MessageBox.Show("获取数据表失败: " + ex.Message);
            } finally {
                if (tables.Items.Contains("cdb_bus"))
                {
                    checkedListBox1.Enabled = true;
                }
                else
                {
                    checkedListBox1.Enabled      = false;
                    checkedListBox1.SelectedItem = null;
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Ejemplo n.º 19
0
        //Метод выполняющий команду и возвращающий результат в виде массива
        public static List <PdfDescription> ExecuteAndReadFilesDescription(string query)
        {
            using (var conn = new MySqlConnection(ConnectionString()))
            {
                //Открываем соединение
                conn.Open();
                conn.ChangeDatabase(Settings.Default.dbName);

                var cmd    = new MySqlCommand(query, conn);
                var reader = cmd.ExecuteReader();

                //Cоздаем необходимые переменные
                var newList = new List <PdfDescription>();

                while (reader.Read())
                {
                    //Присвоими полученные от SQL значения соответсвующему классу
                    var curFile = new PdfDescription
                    {
                        Id = Convert.ToInt32(reader.GetString(0)),
                        PublicationName = reader.GetString(1),
                        IsMagazine      = Convert.ToBoolean(reader.GetString(2)),
                        Date            = Convert.ToDateTime(reader.GetString(3)),
                        IssueNumber     = Convert.ToInt32(reader.GetString(4)),
                        FilePath        = reader.GetString(5)
                    };

                    //Запишем данные в массив
                    newList.Add(curFile);
                }
                return(newList);
            }
        }
Ejemplo n.º 20
0
        internal string Verbinden(string connectstring)
        {
            string result;

            try
            {
                connection = new MySqlConnection(connectstring);
                command    = connection.CreateCommand();
                connection.Open();
                connection.ChangeDatabase("haushaltsbuch");

                _familienmitglied = GetFamilie();
                alleLaeden        = GetLaeden();
                kategorien        = GetKategorien();
                _einnahmen        = GetEinkommen();

                result = "Verbunden";
            }
            catch (MySqlException error)
            {
                result = error.Message;
            }
            IstVerbunden = connection.State == System.Data.ConnectionState.Open;
            return(result);
        }
Ejemplo n.º 21
0
        public override void OnHandel(ExtractResults results)
        {
            var con = new MySqlConnection(Crawler.MysqlConfig.ConString);

            con.Open();
            con.ChangeDatabase(DatabaseName);
            var cmd = new MySqlCommand {
                Connection = con
            };

            //建立文本

            var keys   = "timestamp,cname";
            var values = $"\"{ results.Timestamp}\",\"{Config.Name}\"";

            foreach (var result in results)
            {
                keys   += $",{result.Key}";
                values += $",\"{result.Value}\"";
            }
            try
            {
                cmd.CommandText = $"INSERT INTO {DataTableName}({keys}) VALUES({values})";
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Logger.Error("sql保存错误:" + e.Message);
            }
            con.Close();
        }
Ejemplo n.º 22
0
        //µÃǨÊͺÇèÒÁÕµÒÃÒ§·Õè¡Ó˹´ËÃ×ÍäÁè
        public bool hasTable(string DBname, string TableName, string ConnString)
        {
            MySqlConnection conn = this.Connecting(ConnString);

            if (conn != null)
            {
                try
                {
                    conn.ChangeDatabase(DBname);
                    MySqlCommand comm = conn.CreateCommand();

                    comm.CommandText = "show tables";
                    MySqlDataReader aReader = comm.ExecuteReader();
                    while (aReader.Read())
                    {
                        if (aReader[0].Equals(TableName))
                        {
                            conn.Close();
                            return(true);
                        }
                    }
                    conn.Close();
                }
                catch (MySqlException err)
                {
                    if (conn != null)
                    {
                        conn.Close();
                        conn.Dispose();
                        conn = null;
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 23
0
 public static void CheckDatabase(MySqlConnection connection, string database)
 {
     if (connection.Database != database)
     {
         connection.ChangeDatabase(database);
     }
 }
Ejemplo n.º 24
0
        public static void choosedatabase()
        { // WELKE DATABASE WIL JE IN
            Console.WriteLine("Which database do you want to access:");
            string acDB = Console.ReadLine();

            dbConn.Open();
            dbConn.ChangeDatabase(acDB);

            Console.Clear();

            //SHOW TABLES IN SELECTED DB
            MySqlCommand comd = dbConn.CreateCommand();

            comd.CommandText = "SHOW TABLES";
            MySqlDataReader TobReader;

            TobReader = comd.ExecuteReader();
            while (TobReader.Read())
            {
                string raw = "";
                for (int q = 0; q < TobReader.FieldCount; q++)
                {
                    for (int y = 0; y < TobReader.FieldCount; y++)
                    {
                        raw += TobReader.GetValue(y).ToString() + ", ";
                        Console.WriteLine("{0}", raw);
                    }
                }
            }
            dbConn.Close();
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 查询数据到datatable
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public List <ZhengwenInfo> GetDataFromTable(string str_sql)
        {
            List <ZhengwenInfo> list = new List <ZhengwenInfo>();

            try
            {
                mysql.ChangeDatabase("qianhai");
                MySqlCommand mycmd    = new MySqlCommand(str_sql, mysql);
                var          myreader = mycmd.ExecuteReader();
                while (myreader.Read())
                {
                    ZhengwenInfo zwinfo = new ZhengwenInfo()
                    {
                        _xuhao           = myreader.GetString(0),
                        _bianhao         = myreader.GetString(1),
                        _laiyuan         = myreader.GetString(2),
                        _zhuanzailiang   = myreader.GetString(3),
                        _zhengwenneirong = myreader.GetString(4),
                        _shijian         = myreader.GetString(5),
                        _riqi            = myreader.GetString(6),
                    };


                    list.Add(zwinfo);
                }
                myreader.Close();
            }
            catch { }
            return(list);
        }
Ejemplo n.º 26
0
        //Метод для создания БД и таблицы, если они отсутсвуют
        public static void DataBaseCreate()
        {
            //Откроем новое соединение
            using (var conn = new MySqlConnection(ConnectionString()))
            {
                conn.Open();

                //Запрос для создания базы данных
                var query = "CREATE DATABASE IF NOT EXISTS " +
                            "`" + Settings.Default.dbName +
                            "` CHARACTER SET utf8 COLLATE utf8_general_ci;";
                //Отправляем запрос
                var cmd = new MySqlCommand(query, conn);
                cmd.ExecuteNonQuery();

                //Выбираем БД с которой будем работать
                conn.ChangeDatabase(Settings.Default.dbName);

                //Запрос для создания таблицы
                query = "CREATE TABLE IF NOT EXISTS `" +
                        Settings.Default.dbTableName +            //Имя таблицы
                        "` (" +
                        "`id` INT(6) NOT NULL AUTO_INCREMENT, " + //Автоинкрементирующееся поле id
                        "`publication` VARCHAR(255) NOT NULL, " + //Название издания
                        "`is_magazine` TINYINT(1) NOT NULL, " +   //Журнал или газета
                        "`date` DATETIME NOT NULL, " +            //Дата выхода издания
                        "`issue_number` INT(6) NOT NULL, " +      //Сквозной номер издания
                        "`file_path` VARCHAR(255) NOT NULL, " +   //Расположение файла
                        "PRIMARY KEY(`id`) " +
                        ") ";
                //Отправляем запрос
                cmd = new MySqlCommand(query, conn);
                cmd.ExecuteNonQuery();
            }
        }
Ejemplo n.º 27
0
        private void createDatabase()
        {
            Boolean vorhanden = false;
            string  pCommand  = "SHOW DATABASES;";             // gib die namen der Databases zurück

            foreach (string dbname in executeReader(pCommand)) // es wird geschaut, ob es eine Datenbank mit dem Namen "gammelgames" gibt
            {
                if (dbname == datenbankName)
                {
                    vorhanden = true;
                }
            }

            if (vorhanden == false)  // falls nicht, wird eine Datenbank erstellt
            {
                pCommand = "CREATE DATABASE " + datenbankName + ";";
                executeQuarry(pCommand);

                pCommand = "CREATE TABLE `" + datenbankName + "`.`User` ( `UserID` INT NOT NULL AUTO_INCREMENT, `UserName` VARCHAR(255) NOT NULL, `UserPassword` VARCHAR(255) NOT NULL, PRIMARY KEY(`UserID`)) ENGINE = InnoDB;";
                executeQuarry(pCommand);

                pCommand = "CREATE TABLE `" + datenbankName + "`.`Freundesliste` ( `ListID` INT NOT NULL AUTO_INCREMENT, `UserID` INT(11) NOT NULL, `FreundID` INT(11) NOT NULL, PRIMARY KEY(`ListID`)) ENGINE = InnoDB;";
                executeQuarry(pCommand);

                pCommand = "CREATE TABLE `" + datenbankName + "`.`bibliothek` ( `BibID` INT(11) NOT NULL AUTO_INCREMENT , `UserID` INT(11) NOT NULL , `SpielID` INT(11) NOT NULL , PRIMARY KEY (`BibID`)) ENGINE = InnoDB;";
                executeQuarry(pCommand);

                pCommand = "CREATE TABLE `" + datenbankName + "`.`spiel` ( `SpielID` INT NOT NULL AUTO_INCREMENT, `SpielTitel` VARCHAR(255) NOT NULL, `SpielBeschreibung` TEXT NULL, PRIMARY KEY(`SpielID`)) ENGINE = InnoDB;";
                executeQuarry(pCommand);
            }                             // und in sie gewechselt

            conn.Open();
            conn.ChangeDatabase(datenbankName);
            conn.Close();
        }
Ejemplo n.º 28
0
        public void ChangeDatabaseNotOpen()
        {
            var csb = AppConfig.CreateConnectionStringBuilder();

            using var connection = new MySqlConnection(csb.ConnectionString);
            Assert.Throws <InvalidOperationException>(() => connection.ChangeDatabase(AppConfig.SecondaryDatabase));
        }
Ejemplo n.º 29
0
        public void ReclaimBrokenConnection()
        {
            // now create a new connection string only allowing 1 connection in the pool
            string connStr = ConnectionSettings.ConnectionString + ";connect timeout=1;max pool size=1";

            // now use up that connection
            MySqlConnection c = new MySqlConnection(connStr);

            c.Open();

            // now attempting to open a connection should fail
            MySqlConnection c2 = new MySqlConnection(connStr);
            Exception       ex = Assert.Throws <MySqlException>(() => c2.Open());

            Assert.True(ex.Message.Contains("error connecting: Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool."));

            // we now kill the first connection to simulate a server stoppage
            KillConnection(c);

            // now we do something on the first connection

            ex = Assert.Throws <InvalidOperationException>(() => c.ChangeDatabase("mysql"));
            Assert.True(ex.Message.Contains("The connection is not open."));

            // Opening a connection now should work
            MySqlConnection connection = new MySqlConnection(connStr);

            connection.Open();
            KillConnection(connection);
            connection.Close();
        }
Ejemplo n.º 30
0
        public static MySqlConnection GetConnection()
        {
            MySqlConnection connection;

            try
            {
                Dictionary <string, string> defaults = new Dictionary <string, string>();
                defaults.Add("connectionString", "datasource=localhost;port=3306;username=talky;password=talky;");
                defaults.Add("database", "talky");

                ConfigurationFile config = new ConfigurationFile("database");
                if (!config.Exists())
                {
                    config.Write(defaults);
                }

                string connectionString;
                string db;
                config.Values(defaults).TryGetValue("connectionString", out connectionString);
                config.Values(defaults).TryGetValue("database", out db);

                connection = new MySqlConnection(connectionString);
                connection.Open();
                connection.ChangeDatabase(db);

                return(connection);
            } catch (MySqlException e)
            {
                Program.Instance.OHGODNO("Terminate!! Could not connect to MySQL!! Danger!! Danger!!", e);
                return(null);
            }
        }
Ejemplo n.º 31
0
            private void init(string connString)
            {
                connection = new MySqlConnection(connString);
                connection.Open();
                connection.ChangeDatabase(Server.MySQLDatabaseName);

                transaction = connection.BeginTransaction();
            }
Ejemplo n.º 32
0
 internal static void fill(string queryString, DataTable toReturn)
 {
     using (var conn = new MySqlConnection(connString)) {
         conn.Open();
         conn.ChangeDatabase(Server.MySQLDatabaseName);
         using (MySqlDataAdapter da = new MySqlDataAdapter(queryString, conn)) {
             da.Fill(toReturn);
         }
         conn.Close();
     }
 }
Ejemplo n.º 33
0
 internal static void execute(string queryString, bool createDB = false)
 {
     using (var conn = new MySqlConnection(connString)) {
         conn.Open();
         if (!createDB) {
             conn.ChangeDatabase(Server.MySQLDatabaseName);
         }
         using (MySqlCommand cmd = new MySqlCommand(queryString, conn)) {
             cmd.ExecuteNonQuery();
             conn.Close();
         }
     }
 }
Ejemplo n.º 34
0
        public void ReclaimBrokenConnection()
        {
            // now create a new connection string only allowing 1 connection in the pool
            string connStr = GetPoolingConnectionString() + ";connect timeout=2;max pool size=1";

            // now use up that connection
            MySqlConnection c = new MySqlConnection(connStr);
            c.Open();

            // now attempting to open a connection should fail
            try
            {
                MySqlConnection c2 = new MySqlConnection(connStr);
                c2.Open();
                Assert.Fail("Open after using up pool should fail");
            }
            catch (Exception) { }

            // we now kill the first connection to simulate a server stoppage
            base.KillConnection(c);

            // now we do something on the first connection
            try
            {
                c.ChangeDatabase("mysql");
                Assert.Fail("This change database should not work");
            }
            catch (Exception) { }

            // Opening a connection now should work
            MySqlConnection connection = new MySqlConnection(connStr);
            connection.Open();
            KillConnection(connection);
            connection.Close();
        }
        public void ChangeDatabase()
        {
            string connStr = GetConnectionString(true);
            MySqlConnection c = new MySqlConnection(connStr + ";pooling=false");
            c.Open();
            Assert.IsTrue(c.State == ConnectionState.Open);

            Assert.AreEqual(database0.ToLower(), c.Database.ToLower());

            c.ChangeDatabase(database1);

            Assert.AreEqual(database1.ToLower(), c.Database.ToLower());

            c.Close();
        }