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


C# MySqlCommand.ExecuteScalar方法代码示例

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


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

示例1: InserirPedido

        public int InserirPedido(int numCliente, List<Item> pedido)
        {
            int NumPedido = 0;
            int idPedido = 0;
            MySqlConnection conn = new MySqlConnection(connectionString);
            MySqlCommand cmd = new MySqlCommand();

            cmd.Connection = conn;
            conn.Open();

            cmd.CommandText = "Select Max(numero) + 1 from tb_Pedidos";
            NumPedido = int.Parse(cmd.ExecuteScalar().ToString());

            cmd.CommandText = "Insert into tb_Pedidos (numero, id_cliente, data) Values(" + NumPedido + "," + numCliente + ", sysdate()); select Max(id) from tb_Pedidos;";
            idPedido = int.Parse(cmd.ExecuteScalar().ToString());

            foreach (Item item in pedido)
            {
                cmd.CommandText = "insert into tb_items (nome, descricao, preco, quantidade, id_pedido, urlImagem) Values ('" + item.descricao + "', Null,"+ item.preco.ToString().Replace(",",".") + "," + item.quantidade + "," + idPedido + ", Null);";
                cmd.ExecuteNonQuery();
            }

            conn.Close();

            return NumPedido;
        }
开发者ID:JulioSI,项目名称:TP_Carefour,代码行数:26,代码来源:PedidoDAO.cs

示例2: InsertTest

		public void InsertTest()
		{
			try 
			{
				// do the insert
				MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id,name) VALUES(10,'Test')", conn);
				int cnt = cmd.ExecuteNonQuery();
				Assert.AreEqual( 1, cnt, "Insert Count" );

				// make sure we get the right value back out
				cmd.CommandText = "SELECT name FROM Test WHERE id=10";
				string name = (string)cmd.ExecuteScalar();
				Assert.AreEqual( "Test", name, "Insert result" );

				// now do the insert with parameters
				cmd.CommandText = "INSERT INTO Test (id,name) VALUES(?id, ?name)";
				cmd.Parameters.Add( new MySqlParameter("?id", 11));
				cmd.Parameters.Add( new MySqlParameter("?name", "Test2"));
				cnt = cmd.ExecuteNonQuery();
				Assert.AreEqual( 1, cnt, "Insert with Parameters Count" );

				// make sure we get the right value back out
				cmd.Parameters.Clear();
				cmd.CommandText = "SELECT name FROM Test WHERE id=11";
				name = (string)cmd.ExecuteScalar();
				Assert.AreEqual( "Test2", name, "Insert with parameters result" );
			}
			catch (MySqlException ex)
			{
				Assert.Fail( ex.Message );
			}
		}
开发者ID:LittlePeng,项目名称:ncuhome,代码行数:32,代码来源:CommandTests.cs

示例3: InsertTest

		public void InsertTest()
		{
            execSQL("CREATE TABLE Test (id int NOT NULL, name VARCHAR(100))");
            // do the insert
			MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id,name) VALUES(10,'Test')", conn);
			int cnt = cmd.ExecuteNonQuery();
			Assert.AreEqual( 1, cnt, "Insert Count" );

			// make sure we get the right value back out
			cmd.CommandText = "SELECT name FROM Test WHERE id=10";
			string name = (string)cmd.ExecuteScalar();
			Assert.AreEqual( "Test", name, "Insert result" );

			// now do the insert with parameters
			cmd.CommandText = "INSERT INTO Test (id,name) VALUES(?id, ?name)";
			cmd.Parameters.Add( new MySqlParameter("?id", 11));
			cmd.Parameters.Add( new MySqlParameter("?name", "Test2"));
			cnt = cmd.ExecuteNonQuery();
			Assert.AreEqual( 1, cnt, "Insert with Parameters Count" );

			// make sure we get the right value back out
			cmd.Parameters.Clear();
			cmd.CommandText = "SELECT name FROM Test WHERE id=11";
			name = (string)cmd.ExecuteScalar();
			Assert.AreEqual( "Test2", name, "Insert with parameters result" );
		}
开发者ID:elevate,项目名称:mysqlconnector-.net,代码行数:26,代码来源:CommandTests.cs

示例4: UpdateTest

		public void UpdateTest()
		{
            execSQL("CREATE TABLE Test (id int NOT NULL, name VARCHAR(100))");
            execSQL("INSERT INTO Test (id,name) VALUES(10, 'Test')");
			execSQL("INSERT INTO Test (id,name) VALUES(11, 'Test2')");

			// do the update
			MySqlCommand cmd = new MySqlCommand("UPDATE Test SET name='Test3' WHERE id=10 OR id=11", conn);
			MySqlConnection c = cmd.Connection;
			Assert.AreEqual(conn, c);
			int cnt = cmd.ExecuteNonQuery();
			Assert.AreEqual(2, cnt);

			// make sure we get the right value back out
			cmd.CommandText = "SELECT name FROM Test WHERE id=10";
			string name = (string)cmd.ExecuteScalar();
			Assert.AreEqual("Test3", name);
		
			cmd.CommandText = "SELECT name FROM Test WHERE id=11";
			name = (string)cmd.ExecuteScalar();
			Assert.AreEqual("Test3", name);

			// now do the update with parameters
			cmd.CommandText = "UPDATE Test SET name=?name WHERE id=?id";
			cmd.Parameters.Add( new MySqlParameter("?id", 11));
			cmd.Parameters.Add( new MySqlParameter("?name", "Test5"));
			cnt = cmd.ExecuteNonQuery();
			Assert.AreEqual(1, cnt, "Update with Parameters Count");

			// make sure we get the right value back out
			cmd.Parameters.Clear();
			cmd.CommandText = "SELECT name FROM Test WHERE id=11";
			name = (string)cmd.ExecuteScalar();
			Assert.AreEqual("Test5", name);
		}
开发者ID:elevate,项目名称:mysqlconnector-.net,代码行数:35,代码来源:CommandTests.cs

示例5: CallingStoredProcWithOnlyExecPrivs

    public void CallingStoredProcWithOnlyExecPrivs()
    {
      if (Version < new Version(5, 0)) return;

      execSQL("CREATE PROCEDURE spTest() BEGIN SELECT 1; END");
      execSQL("CREATE PROCEDURE spTest2() BEGIN SELECT 1; END");
      suExecSQL(String.Format("GRANT USAGE ON `{0}`.* TO 'abc'@'%' IDENTIFIED BY 'abc'", database0));

      try
      {
        suExecSQL(String.Format("GRANT SELECT ON `{0}`.* TO 'abc'@'%'", database0));
        suExecSQL(String.Format("GRANT EXECUTE ON PROCEDURE `{0}`.spTest TO abc", database0));

        string connStr = GetConnectionString("abc", "abc", true) + "; check parameters=false";

        using (MySqlConnection c = new MySqlConnection(connStr))
        {
          c.Open();
          MySqlCommand cmd = new MySqlCommand("spTest", c);
          cmd.CommandType = CommandType.StoredProcedure;
          object o = null;
          Assert.DoesNotThrow(delegate { o = cmd.ExecuteScalar(); });
          Assert.AreEqual(1, o);

          cmd.CommandText = "spTest2";
          Assert.Throws(typeof(MySqlException), delegate { cmd.ExecuteScalar(); });
        }
      }
      finally
      {
        suExecSQL("DROP USER abc");
      }
    }
开发者ID:jimmy00784,项目名称:mysql-connector-net,代码行数:33,代码来源:StoredProcedureWithAccess.cs

示例6: ExecuteQuery

 public string ExecuteQuery(string Query)
 {
     connection.Open();
     MySqlCommand command = new MySqlCommand(Query);
     command.Connection = this.connection;
     String res = "";
     if (command.ExecuteScalar() != null) res = command.ExecuteScalar().ToString();
     connection.Close();
     if (res == "") res = "-1";
     return res;
 }
开发者ID:sokac237,项目名称:Barun-trenk,代码行数:11,代码来源:upiti.cs

示例7: CreateBank

        public int CreateBank(Bank b)
        {
            int ret = 0;
            using (connect = new MySqlConnection(_connectionString))
            {
                connect.Open();
                using (MySqlTransaction transaction = connect.BeginTransaction())
                {

                    try
                    {
                        string query = "NewBank";
                        var cmd = new MySqlCommand(query, connect) { CommandType = CommandType.StoredProcedure };

                        cmd.Parameters.AddWithValue("SortCode", b.SortCode);
                        cmd.Parameters.AddWithValue("AccountNumber", b.ID);

                        ret = int.Parse(cmd.ExecuteScalar().ToString());

                        transaction.Commit();

                        connect.Close();
                    }
                    catch (InvalidOperationException ioException)
                    {
                        transaction.Rollback();
                        connect.Close();
                    }
                }
            }
            return ret;
        }
开发者ID:campbellre,项目名称:TWART,代码行数:32,代码来源:BankingModel.cs

示例8: GetNumberOfRowsInATable

        public static int GetNumberOfRowsInATable()
        {
            int numberOfRows = 0;
            try
            {
                string mySqlConnectionString = MakeMySqlConnectionString();
                var conn = new MySqlConnection {ConnectionString = mySqlConnectionString};

                using (var cmd = new MySqlCommand("SELECT COUNT(*) FROM " + Program.selectedEventName, conn))
                {
                    conn.Open();
                    numberOfRows = int.Parse(cmd.ExecuteScalar().ToString());
                    conn.Close();
                    cmd.Dispose();
                    return numberOfRows;
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine(ex.Message);
                ConsoleWindow.WriteLine("Error Code: " + ex.ErrorCode);
                ConsoleWindow.WriteLine(ex.Message);
            }
            return numberOfRows;
        }
开发者ID:AdiSai,项目名称:FRC_Scouting_V2,代码行数:26,代码来源:MySQLMethods.cs

示例9: sprAdmin

    protected bool sprAdmin(int id)
    {
        string connStr = ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString;
        MySqlConnection conn = new MySqlConnection(connStr);

        try
        {
            conn.Open();

            string sql = "SELECT typ FROM users WHERE [email protected];";
            MySqlCommand zapytanie = new MySqlCommand(sql, conn);

            zapytanie.Parameters.Add(new MySqlParameter("@Id", Session["id"].ToString()));

            object wynik = zapytanie.ExecuteScalar();

            if (wynik != null && wynik.ToString() == "A")
            {
                conn.Close();
                return true;
            }

            conn.Close();
        }
        catch (MySqlException ex)
        {
            //Blad.InnerHtml = ex.ToString();
        }

        return false;
    }
开发者ID:EddyEND,项目名称:Przychodnia_empty,代码行数:31,代码来源:MasterAdmin.master.cs

示例10: CreateUser

        public int CreateUser(User u)
        {
            int ret = 0;
            using (connect = new MySqlConnection(_connectionString))
            {
                connect.Open();
                using (MySqlTransaction transaction = connect.BeginTransaction())
                {

                    try
                    {
                        string query = "NewUserAccount";
                        var cmd = new MySqlCommand(query, connect) { CommandType = CommandType.StoredProcedure };

                        cmd.Parameters.AddWithValue("PUsername", u.username);
                        cmd.Parameters.AddWithValue("PPWD", u.password);
                        cmd.Parameters.AddWithValue("EmployeeID", u.EmployeeID);

                        ret = int.Parse(cmd.ExecuteScalar().ToString());

                        transaction.Commit();

                        connect.Close();
                    }
                    catch (InvalidOperationException ioException)
                    {
                        transaction.Rollback();

                        connect.Close();
                    }
                }
            }
            return ret;
        }
开发者ID:campbellre,项目名称:TWART,代码行数:34,代码来源:LoginModel.cs

示例11: GetNumberOfRowsThatContainAValue

        public static int GetNumberOfRowsThatContainAValue(int teamNumber)
        {
            int numberOfRows = 0;
            try
            {
                string mySqlConnectionString = MakeMySqlConnectionString();
                var conn = new MySqlConnection {ConnectionString = mySqlConnectionString};

                string mySQLCommantText = String.Format("SELECT COUNT(*) FROM {0} WHERE TeamNumber={1}", Program.selectedEventName, teamNumber);
                using (var cmd = new MySqlCommand(mySQLCommantText, conn))
                {
                    conn.Open();
                    numberOfRows = int.Parse(cmd.ExecuteScalar().ToString());
                    conn.Close();
                    cmd.Dispose();
                    return numberOfRows;
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine("Error Code: " + ex.ErrorCode);
                Console.WriteLine(ex.Message);
            }
            return numberOfRows;
        }
开发者ID:AdiSai,项目名称:FRC_Scouting_V2,代码行数:25,代码来源:MySQLMethods.cs

示例12: btn_save_Click

        private void btn_save_Click(object sender, EventArgs e)
        {
            connection = new MySqlConnection(ConnectionString);  

            if (txt_fname.Text == "" || txt_lname.Text == "" || mcmb_status.Text == "")
            {
                string myStringVariable1 = string.Empty;
                MetroMessageBox.Show(this, "Field is Empty");
                return;
            }
            connection.Open();

            string str = "Select count(*) from employee_info where em_fname = '" + txt_fname.Text + "' and em_lname = '" + txt_lname.Text + "'";
            MySqlCommand cmd = new MySqlCommand(str, connection);
            int userExist = Convert.ToInt32(cmd.ExecuteScalar());
            if (userExist > 0)
            {
                MetroMessageBox.Show(this, "Employee already exist");
                btn_cancel.PerformClick();
                return;
            }

            connection.Close();
            Insert();
        }
开发者ID:TinaOporto,项目名称:InventorySystem,代码行数:25,代码来源:AddEmployee.cs

示例13: retrieveAlbumId

        public int retrieveAlbumId()
        {
            DBConnect connection = new DBConnect();

            string query = "SELECT albumId FROM Album WHERE albumName LIKE @albumName;";

            try
            {
                MySqlCommand cmd = new MySqlCommand(query, connection.OpenConnection());
                cmd.CommandText = query;
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@albumName", this.albumName);

                albumId = int.Parse(cmd.ExecuteScalar() + "");

                cmd.ExecuteNonQuery();

                connection.CloseConnection();

                return albumId;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
开发者ID:altaria,项目名称:Altaria,代码行数:26,代码来源:Album.cs

示例14: button1_Click

        private void button1_Click(object sender, EventArgs e)
        {
            using (MySqlConnection con = new MySqlConnection(connectionString))
            {
                try
                {
                    con.Open();
                    string query = "SELECT VERSION()";
                    MySqlCommand cmd = new MySqlCommand(query, con);
                    string version = Convert.ToString(cmd.ExecuteScalar());
                    //Console.WriteLine("MySQL version : {0}", version);
                    label1.Text = "Connection Established!\n" + "MySQL Version: " + version;

                }
                catch (Exception ex)
                {
                    label1.Text = "Connection Error!\n" + ex.Message;
                }
                //I am using 'using', so wouldn't need the finally block, for the using function
                //will close the connection automatically.
                //finally
                //{
                //    con.close();
                //}
            }
        }
开发者ID:Ali-Shaikh,项目名称:MySQLConnection,代码行数:26,代码来源:FrmConnection.cs

示例15: saveStatus

        public void saveStatus()
        {
            //p_save_status_media
            try
            {
                using (MySqlConnection conn = new MySqlConnection(App.setting.connectString))
                {
                    conn.Open();
                    string query = "`p_save_status_media`";
                    using (MySqlCommand cmd = new MySqlCommand(query, conn))
                    {
                        cmd.Parameters.Add(new MySqlParameter("@_media_id", MySqlDbType.Int32) { Direction = System.Data.ParameterDirection.Input, Value = this.ID });
                        cmd.Parameters.Add(new MySqlParameter("@_status", MySqlDbType.Int16) { Direction = System.Data.ParameterDirection.Input, Value = this.Status });
                        //_status
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.ExecuteScalar();
                    };
                    conn.Close();
                };

            }
            catch (Exception)
            {
            }
        }
开发者ID:iceriver102,项目名称:alta-mtc-version-2,代码行数:25,代码来源:MediaFunction.cs


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