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


C# SqlCommand.BeginExecuteNonQuery方法代码示例

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


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

示例1: Confirmation

        protected void Confirmation(object sender, EventArgs e)
        {
            Customer cust = new Customer();
            List<Customer> customersList = Application["CustomerList"] as List<Customer>;

            cust.EmailAddress = email.Text.ToString();
            cust.Password = pass1.Text.ToString();
            cust.LastName = lname.Text.ToString();
            cust.FirstName = fname.Text.ToString();
            cust.FullAddress = address1.Text.ToString();
            cust.ContactPhone = phone.Text.ToString();

              SqlConnection connect = new SqlConnection("Data Source=dcm.uhcl.edu;Initial Catalog=c423013fa01kannegantis;User id=kannegantis;Password=1187207;Persist Security Info=True");
              String Stat = "insert into KannegantiS_WADfl13_Customers(emailAddress,password,firstName,lastName,fullAddress,contactPhone) values('" + cust.EmailAddress + "','" + cust.Password + "','" + cust.FirstName + "','" + cust.LastName + "','" + cust.FullAddress + "','" + cust.ContactPhone + "')";
            SqlCommand sc = new SqlCommand(Stat, connect);
            try
            {
                connect.Open();
                sc.CommandText = Stat;
                sc.BeginExecuteNonQuery();
                //System.Data.SqlClient.SqlDataReader sqlReader = sc.ExecuteReader();

            }
            finally
            {
                connect.Close();
            }

              Session["currentCutomer"] = cust;

            customersList.Add(cust);

            ClientScript.RegisterStartupScript(GetType(), "TestAlert", "alert(\'Thank you for creating an account.Please click the \\'Go to Main Page\\' button below and click \\'My Account\\' on the main page to Login.\');", true);
        }
开发者ID:kannchinna,项目名称:Universal-Calling-Card,代码行数:34,代码来源:signup.aspx.cs

示例2: EliminarAlumno

        public bool EliminarAlumno( string Codigo)
        {
            //Creo el nuevo objeto SQLconexion a la variable StrConexion.

            try
            {
                Conexion = new SqlConnection("Data Source = localhost; Initial Catalog = BDAcademico; Integrated Security = True");

                string sql = "DELETE FROM TablaAlumnos WHERE Codigo = '" + Codigo +"'";

                SqlCommand cmd = new SqlCommand(sql, Conexion);

                Conexion.Open();

                cmd.BeginExecuteNonQuery();

                return true;

            }

            catch (Exception ex)
            {

                return false;
            }

            Conexion.Close();
        }
开发者ID:Gsaico,项目名称:Laboratorio_10,代码行数:28,代码来源:ConsultaBD.cs

示例3: RunCommandCount

        public int RunCommandCount(string commandText)
        {
            using (SqlConnection connection =
                new SqlConnection(connectionString))
            {
                try
                {
                    SqlCommand command = new SqlCommand(commandText, connection);
                    connection.Open();

                    IAsyncResult result = command.BeginExecuteNonQuery();

                    return command.EndExecuteNonQuery(result);
                }
                catch (InvalidOperationException ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);

                    return 0;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);

                    return 0;
                }
            }
        }
开发者ID:hehaiyang7133862,项目名称:VICO_Current,代码行数:28,代码来源:SqlHelper.cs

示例4: bttnClearDatabase_Click

        private void bttnClearDatabase_Click(object sender, EventArgs e)
        {
            string destroyTable = "DROP TABLE Records;";
            SqlCommand myCommand;
            myCommand = new SqlCommand();
            myCommand.CommandText = destroyTable;
            myCommand.Connection = myConnection;

                myCommand.BeginExecuteNonQuery();

            while (listBoxRecords.Items.Count != 0)
            {
                listBoxRecords.Items.RemoveAt(0);
            }
        }
开发者ID:gregoryenriquez,项目名称:Programming-Code-Examples,代码行数:15,代码来源:Form1.cs

示例5: BeginExecuteNonQuery

        /// <summary> Execute an asynchronous non-query SQL statement or stored procedure </summary>
        /// <param name="DbType"> Type of database ( i.e., MSSQL, PostgreSQL ) </param>
        /// <param name="DbConnectionString"> Database connection string </param>
        /// <param name="DbCommandType"> Database command type </param>
        /// <param name="DbCommandText"> Text of the database command, or name of the stored procedure to run </param>
        /// <param name="DbParameters"> Parameters for the SQL statement </param>
        public static void BeginExecuteNonQuery(EalDbTypeEnum DbType, string DbConnectionString, CommandType DbCommandType, string DbCommandText, List<EalDbParameter> DbParameters)
        {
            if (DbType == EalDbTypeEnum.MSSQL)
            {
                // Create the SQL connection
                SqlConnection sqlConnect = new SqlConnection(DbConnectionString);
                try
                {
                    sqlConnect.Open();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("Unable to open connection to the database." + Environment.NewLine + ex.Message, ex);
                }

                // Create the SQL command
                SqlCommand sqlCommand = new SqlCommand(DbCommandText, sqlConnect)
                {
                    CommandType = DbCommandType
                };

                // Copy all the parameters to this adapter
                sql_add_params_to_command(sqlCommand, DbParameters);

                // Run the command itself
                try
                {
                    sqlCommand.BeginExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException("Error executing non-query command." + Environment.NewLine + ex.Message, ex);
                }

                // Return
                return;
            }

            if (DbType == EalDbTypeEnum.PostgreSQL)
            {
                throw new ApplicationException("Support for PostgreSQL with SobekCM is targeted for early 2016");
            }

            throw new ApplicationException("Unknown database type not supported");
        }
开发者ID:Elkolt,项目名称:SobekCM-Web-Application,代码行数:51,代码来源:EalDbAccess.cs

示例6: bttnCreateDatabase_Click

        private void bttnCreateDatabase_Click(object sender, EventArgs e)
        {
            string createTable = "CREATE TABLE Records " +
                                "(" +
                                "LastName  VARCHAR(20) PRIMARY KEY," +
                                "FirstName VARCHAR(20), " +
                                "Address   VARCHAR(30), " +
                                "City      VARCHAR(20), " +
                                "State     VARCHAR(20), " +
                                "Phone     VARCHAR(20), " +
                                "Zip       VARCHAR(20) " +
                                ");";
            SqlCommand myCommand;
            myCommand = new SqlCommand();
            myCommand.CommandText = createTable;
            myCommand.Connection = myConnection;

            myCommand.BeginExecuteNonQuery();
        }
开发者ID:gregoryenriquez,项目名称:Programming-Code-Examples,代码行数:19,代码来源:Form1.cs

示例7: RunCommandAsynchronously

        private static void RunCommandAsynchronously(
          string commandText, string connectionString)
        {
            using (SqlConnection connection =
              new SqlConnection(connectionString))
            {
                try
                {
                    int count = 0;
                    SqlCommand command = 
                        new SqlCommand(commandText, connection);
                    connection.Open();

                    IAsyncResult result = 
                        command.BeginExecuteNonQuery();
                    while (!result.IsCompleted)
                    {
                        Console.WriteLine(
                                        "Waiting ({0})", count++);
                        // Wait for 1/10 second, so the counter
                        // doesn't consume all available 
                        // resources on the main thread.
                        System.Threading.Thread.Sleep(100);
                    }
                    Console.WriteLine(
                        "Command complete. Affected {0} rows.",
                    command.EndExecuteNonQuery(result));
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error ({0}): {1}", 
                        ex.Number, ex.Message);
                }
                catch (InvalidOperationException ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);
                }
            }
        }
开发者ID:xs2ranjeet,项目名称:13ns9-1spr,代码行数:43,代码来源:Program.cs

示例8: ExcuteNonQueryPreparedStatement

        public static void ExcuteNonQueryPreparedStatement(SqlCommand command)
        {
            if (command == null)
            {
                return;
            }
            //Check for "'" in singular form causing a problem with the SQL Statment
            foreach (object sqlParameter in from object sqlParameter in ((command.Parameters))
                                            from item in
                                                ((IEnumerable) ((SqlParameter) (sqlParameter)).Value).Cast<object>()
                                                                                                     .Where
                                                (
                                                    item => item.ToString()
                                                                .Contains("'"))
                                            select sqlParameter)
            {
            }
            command.StatementCompleted += (SMECustContactCon_StatementCompleted);
            try
            {
                IAsyncResult result = command.BeginExecuteNonQuery();

                while (!result.IsCompleted)
                {
                    Thread.Sleep(100);
                }
                if (command.Connection != null && command.Connection.State == ConnectionState.Closed)
                {
                    return;
                }
                command.EndExecuteNonQuery(result);
            }
            catch (Exception ex)
            {
                MessageDialog.Show
                    (
                        "Error retrieved updating \r\n" + ex.InnerException,
                        "Error",
                        MessageDialog.MessageBoxButtons.Ok,
                        MessageDialog.MessageBoxIcon.Error,
                        "Please Check You Credentials Are Valid" + "\r\n" + ex.StackTrace);
            }
        }
开发者ID:Brett1981,项目名称:ReuseableClasses,代码行数:43,代码来源:Connection.cs

示例9: b_nonworking_Click

        private void b_nonworking_Click(object sender, EventArgs e)
        {
            selectday.Visible = false;
            dropdown.Visible = false;
            lec1.Visible = false;
            lec2.Visible = false;
            lec3.Visible = false;
            lec4.Visible = false;
            lec5.Visible = false;
            lec6.Visible = false;
            lec7.Visible = false;
            dd1.Visible = false;
            dd2.Visible = false;
            dd3.Visible = false;
            dd4.Visible = false;
            dd5.Visible = false;
            dd6.Visible = false;
            dd7.Visible = false;
            saveme.Visible = false;
            save.Visible = false;
            s1.Visible = false;
            s2.Visible = false;
            s3.Visible = false;
            s4.Visible = false;
            s5.Visible = false;
            daywise.Visible = false;
            subwise.Visible = false; 
            rollname.Visible = false;
            l_days.Visible = false;
            m1.Visible = false;
            t_name.Visible = false;
            l_enterroll.Visible = false;
            l_entername.Visible = false;
            t_roll.Visible = false;
            t_name.Visible = false;
            b_submit.Visible = false;
            l_putfinger.Visible = false;
            pictureBox1.Visible = false;
            l_dataenrolled.Visible = false;
            m1.Visible = false;
            m2.Visible = false;
            m3.Visible = false;
            m4.Visible = false;
            m5.Visible = false;
            m6.Visible = false;
            m7.Visible = false;
            m8.Visible = false;
            m9.Visible = false;
            m10.Visible = false;
            m11.Visible = false;
            m12.Visible = false;
            m13.Visible = false;
            m14.Visible = false;
            m15.Visible = false;
            m16.Visible = false;
            m17.Visible = false;
            m18.Visible = false;
            m19.Visible = false;
            m20.Visible = false;
            m21.Visible = false;
            m22.Visible = false;
            m23.Visible = false;
            m24.Visible = false;
            m25.Visible = false;
            m26.Visible = false;
            m27.Visible = false;
            m28.Visible = false;
            m29.Visible = false;
            m30.Visible = false;
            m31.Visible = false;
            
          


            studentlist.Visible = false;


            con.Open();


            SqlCommand selcmd1 = new System.Data.SqlClient.SqlCommand(" INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=c:\\Test.xls;','select roll_no,name from studentdatabase.dbo.student3')", con);

            selcmd1.BeginExecuteNonQuery();
            con.Close();


        }
开发者ID:Jain-Nidhi,项目名称:Fingerprint-Recognition-using-Minutae-matching,代码行数:87,代码来源:Form1.cs

示例10: UpdateCityForCharacter

 /// <summary>
 /// Updates the City field in the DB for a particular character.
 /// </summary>
 /// <param name="CharacterName">The name of the character to update.</param>
 /// <param name="AccountName">The name of the account that has the character.</param>
 /// <param name="CityName">The name of the city the character resides in.</param>
 public static void UpdateCityForCharacter(string CharacterName, string CityName)
 {
     //Gets the data in the Name column.
     SqlCommand Command = new SqlCommand("UPDATE Characters SET City='" + CityName +
         "' WHERE Name='" + CharacterName + "'");
     Command.BeginExecuteNonQuery(new AsyncCallback(EndUpdateCityForCharacter), new DatabaseAsyncObject(CityName,
         CharacterName, Command));
 }
开发者ID:Blayer98,项目名称:Project-Dollhouse,代码行数:14,代码来源:Database.cs

示例11: TestNonExecuteMethod

        private static void TestNonExecuteMethod()
        {
            Console.WriteLine("Staring of Non Execute Method....");
            _reset.Reset();

            try
            {
                using (SqlConnection conn = new SqlConnection(ConnectionStr))
                {
                    using (SqlCommand cmd = new SqlCommand(StoredProc, conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandTimeout = 30;
                        cmd.Connection.InfoMessage += ConnectionInfoMessage;
                        AsyncCallback result = NonQueryCallBack;
                        cmd.Connection.Open();
                        cmd.BeginExecuteNonQuery(result, cmd);
                        Console.WriteLine("Waiting for completion of executing stored procedure....");
                        _reset.WaitOne();
                    }
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Problem with executing command! - [{0}]", ex.Message);
            }
            Console.WriteLine("Completion of Non Execute Method....");
        }
开发者ID:pampero,项目名称:cgControlPanel,代码行数:28,代码来源:Program.cs

示例12: ExecuteNonQuery

 public Sql ExecuteNonQuery(SqlCommand cmd, Action<Exception,int> callback = null)
 {
     cmd.Connection.Open();
     var state = new ExecuteNonQueryState(cmd, callback);
     cmd.BeginExecuteNonQuery(ExecuteNonQueryCallback, state);
     return this;
 }
开发者ID:blesh,项目名称:ALE,代码行数:7,代码来源:Sql.cs

示例13: SampleAsyncMethods

        private static void SampleAsyncMethods()
        {
            IAsyncResult asyncResult;

            /***** SQL Connection *****/
            // NOTE: "Async=true" setting required for asynchronous operations.
            using (SqlConnection connection = new SqlConnection(@"Async=true;Server=SERVER;Database=DATABASE;Integrated Security=true"))
            {
                connection.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT UserId, Name, LastLogIn FROM Users WHERE Email = '[email protected]'", connection))
                {
                    asyncResult = cmd.BeginExecuteReader();
                    // ... query executes asynchronously in background ...
                    using (IDataReader reader = cmd.EndExecuteReader(asyncResult))
                    {
                        // WARNING: The DbAsyncResult object returned by BeginExecuteReader always creates a ManualResetEvent, but
                        // never closes it; after calling EndExecuteReader, the AsyncWaitHandle property is still valid, so we close it explicitly.
                        asyncResult.AsyncWaitHandle.Close();

                        while (reader.Read())
                        {
                            // do stuff
                        }
                    }
                }

                using (SqlCommand cmd = new SqlCommand("UPDATE Users SET LastLogIn = GETUTCDATE() WHERE UserId = 1", connection))
                {
                    asyncResult = cmd.BeginExecuteNonQuery();
                    // ... query executes asynchronously in background ...
                    int rowsAffected = cmd.EndExecuteNonQuery(asyncResult);

                    // WARNING: The DbAsyncResult object returned by BeginExecuteNonQuery always creates a ManualResetEvent, but
                    // never closes it; after calling EndExecuteReader, the AsyncWaitHandle property is still valid, so we close it explicitly.
                    asyncResult.AsyncWaitHandle.Close();
                }
            }

            /***** File Operations *****/
            // NOTE: FileOptions.Asynchronous flag required for asynchronous operations.
            using (Stream stream = new FileStream(@"C:\Temp\test.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096,
                FileOptions.Asynchronous))
            {
                byte[] buffer = new byte[65536];
                asyncResult = stream.BeginRead(buffer, 0, buffer.Length, null, null);
                // ... disk read executes asynchronously in background ...
                int bytesRead = stream.EndRead(asyncResult);
            }

            /***** HTTP Operation *****/
            // WARNING: DNS operations are synchronous, and will block!
            WebRequest request = WebRequest.Create(new Uri(@"http://www.example.com/sample/page"));
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            asyncResult = request.BeginGetRequestStream(null, null);
            // ... connection to server opened in background ...
            using (Stream stream = request.EndGetRequestStream(asyncResult))
            {
                byte[] bytes = Encoding.UTF8.GetBytes("Sample request");
                asyncResult = stream.BeginWrite(bytes, 0, bytes.Length, null, null);
                stream.EndWrite(asyncResult);
            }

            // WARNING: WebRequest will swallow any exceptions thrown from the AsyncCallback passed to BeginGetResponse.
            asyncResult = request.BeginGetResponse(null, null);
            // ... web request executes in background ...
            using (WebResponse response = request.EndGetResponse(asyncResult))
            using (Stream stream = response.GetResponseStream())
            {
                // read response from server
                // WARNING: This code should also use asynchronous operations (BeginRead, EndRead); "Using synchronous calls
                //   in asynchronous callback methods can result in severe performance penalties." (MSDN)
            }

            /***** DNS hostname resolution *****/
            // WARNING: Doesn't truly use async I/O, but simply queues the request to a ThreadPool thread.
            asyncResult = Dns.BeginGetHostEntry("www.example.com", null, null);
            // ... DNS lookup executes in background
            IPHostEntry entry = Dns.EndGetHostEntry(asyncResult);

            /***** Other: Sockets, Serial Ports, SslStream *****/
        }
开发者ID:bgrainger,项目名称:AsyncIoDemo,代码行数:83,代码来源:Program.cs

示例14: InsertToTable

 /// <summary>
 /// Creates and executes a command object for inserting values to a table
 /// </summary>
 /// <param name="insert">The insert SQL string</param>
 public void InsertToTable(string insert)
 {
     SqlCommand cmnd = new SqlCommand(insert, connection);
     connection.Open();
     cmnd.BeginExecuteNonQuery();
 }
开发者ID:jason5hek,项目名称:LoginClassLibrary,代码行数:10,代码来源:DataTableOperations.cs

示例15: BeginExecuteNonQuery

        public static void BeginExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            //create a command and prepare it for execution
            SqlCommand cmd = new SqlCommand();
            
            PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

            cmd.BeginExecuteNonQuery();
            // detach the SqlParameters from the command object, so they can be used again.
            cmd.Parameters.Clear();
        }
开发者ID:geniushuai,项目名称:DDTank-3.0,代码行数:11,代码来源:SqlHelper.cs


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