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


C# SqlCommand.Prepare方法代码示例

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


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

示例1: addAlbum

        public bool addAlbum(string name, int pubYear)
        {
            SqlConnection con = getConnection();
            string result = "OK";
            try
            {
                con.Open();
                string query = "INSERT INTO Album " +
                    "(name, year_published)" +
                        " VALUES (@name, @pub_year)";

                SqlCommand command = new SqlCommand(query, con);
                command.Prepare();
                command.Parameters.AddWithValue("@name", name);
                command.Parameters.AddWithValue("@pub_year", pubYear);

                command.ExecuteNonQuery();

            }
            catch (Exception e)
            {
                result = e.Message;
                return false;
            }
            finally
            {
                con.Close();
                // Log the result
                Console.WriteLine(result);
            }
            return true;
        }
开发者ID:m1ch0,项目名称:IT_Project_Album,代码行数:32,代码来源:Database.cs

示例2: anbieterAktualisieren

        public bool anbieterAktualisieren(Anbieter benutzer)
        {
            string query = "UPDATE Benutzer SET " +
                                "[email protected], " +
                                "[email protected], " +
                                "[email protected] " +
                            "WHERE [email protected]";

            try
            {
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Prepare();
                cmd.Parameters.AddWithValue("@vorname", benutzer.vorname);
                cmd.Parameters.AddWithValue("@nachname", benutzer.nachname);

                cmd.Parameters.AddWithValue("@institut", benutzer.institut);

                cmd.Parameters.AddWithValue("@email", benutzer.email);

                connect();
                cmd.ExecuteNonQuery();
                disconnect();
                return true;
            }
            catch (SqlException e)
            {
                lastError = e.StackTrace;
                Console.WriteLine(e.StackTrace);
                return false;
            }
        }
开发者ID:soerenraeuchle,项目名称:SoPraRep,代码行数:31,代码来源:DBManager.cs

示例3: CountBikesButton_Click

    protected void CountBikesButton_Click(object sender, EventArgs e)
    {
        StringBuilder count = new StringBuilder();
        string fDateTime = FromDate.Text + " " + FromDateTime.Text;
        string tDateTime = ToDate.Text + " " + ToDateTime.Text;

        SqlConnection advbikecountconn = null;
        SqlDataReader advbikecountrdr = null;
        advbikecountconn = new SqlConnection(conStr);
        advbikecountconn.Open();
        // cmd2 RETRIEVE DATA
        SqlCommand advbikecountcmd = new SqlCommand();
        advbikecountcmd.Connection = advbikecountconn;
        advbikecountcmd.CommandText = @"SELECT COUNT(*) FROM rightalertmaster WHERE DateTime >= '" + fDateTime + "' AND DateTime <= '" + tDateTime + "';";
        advbikecountcmd.Prepare();
        advbikecountrdr = advbikecountcmd.ExecuteReader();
        if (advbikecountrdr.HasRows)
        {
            while (advbikecountrdr.Read())
            {
                string num = advbikecountrdr[0].ToString();
                //count.Append("<div class=\"ov - widget__value\"><label>");
                count.Append("Bike Count: " + num.ToString());
                //count.Append("</label></div><div class=\"ov-widget__info\"><div class=\"ov-widget__title\">Bike Count</div></div>");
            }
        }
        advbikecountrdr.Close();
        advbikecountconn.Close();

        CountBikesPlaceHolder.Controls.Add(new Literal { Text = count.ToString() });
    }
开发者ID:sbobhate,项目名称:Right-Alert,代码行数:31,代码来源:Advanced.aspx.cs

示例4: addCVs

        public void addCVs(SqlConnection sql, int id, string path)
        {
            sql.Open();
            using (SqlCommand addCVs = new SqlCommand("INSERT INTO dbo.ExternFile VALUES (1, @idEmployee, @path)", sql))
            {
                addCVs.Parameters.Clear();

                // Parameters
                SqlParameter idEmployeeParam = new SqlParameter("@ID", SqlDbType.Int);
                SqlParameter pathParam = new SqlParameter("@path", SqlDbType.VarChar, 255);

                // Definitions for parameters
                idEmployeeParam.Value = id;
                pathParam.Value = path;

                // Add parameters
                addCVs.Parameters.Add(idEmployeeParam);
                addCVs.Parameters.Add(pathParam);

                // Execute command
                addCVs.Prepare();
                addCVs.ExecuteNonQuery();

                MessageBox.Show("Životopis úspěšně přidán do DB");
            }
            sql.Close();
        }
开发者ID:Rad3k,项目名称:Experiences,代码行数:27,代码来源:Transactions.cs

示例5: AddUserRole

    public void AddUserRole(string roleID = "REGISTERER")
    {
        string connection = ConfigurationManager.ConnectionStrings["EVENTSConnectionString"].ToString();
        SqlConnection dbConnection = new SqlConnection(connection);
        try
        {
            dbConnection.Open();

            SqlParameter EmailParam = new SqlParameter("@EMAIL", System.Data.SqlDbType.NVarChar, 50);
            EmailParam.Value = this.applicationUser.Email;
            SqlParameter RoleParam = new SqlParameter("@ROLE_NAME", System.Data.SqlDbType.NVarChar, 70);
            RoleParam.Value = roleID;
            SqlParameter[] AddRoleParameters = new SqlParameter[] { EmailParam, RoleParam };
            string addRoleCommand = "INSERT INTO USER_ROLE (EMAIL, ROLE_NAME) VALUES (@EMAIL, @ROLE_NAME);";
            SqlCommand addRole = new SqlCommand(null, dbConnection);
            addRole.Parameters.AddRange(AddRoleParameters);
            addRole.CommandText = addRoleCommand;
            addRole.Prepare();
            addRole.ExecuteNonQuery();
            dbConnection.Close();
        }
        catch (SqlException exception)
        {
            // "<p> Error Code " + exception.Number + ": " + exception.Message + "</p>";
        }
    }
开发者ID:movies28423,项目名称:Conference-Register,代码行数:26,代码来源:UserRole.cs

示例6: Comments

        public ActionResult Comments()
        {
            List<string> comments = new List<string>();

            //Get current user from default membership provider
            MembershipUser user = Membership.Provider.GetUser(HttpContext.User.Identity.Name, true);
            if (user != null)
            {
                //Add request param : https://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlcommand.prepare(v=vs.110).aspx
                SqlCommand cmd = new SqlCommand(null, _dbConnection);
                // Create and prepare an SQL statement.
                cmd.CommandText ="Select Comment from Comments where UserId = @user_id";
                SqlParameter idParam = new SqlParameter("@user_id", SqlDbType.UniqueIdentifier);
                idParam.Value = user.ProviderUserKey;
                cmd.Parameters.Add(idParam);
                _dbConnection.Open();
                // Call Prepare after setting the Commandtext and Parameters.
                cmd.Prepare();
                SqlDataReader rd = cmd.ExecuteReader();

                while (rd.Read())
                {
                    comments.Add(rd.GetString(0));
                }

                rd.Close();
                _dbConnection.Close();
            }
            return View(comments);
        }
开发者ID:Uldax,项目名称:SansSoussi,代码行数:30,代码来源:HomeController.cs

示例7: DeleteOpenMessage

    public static void DeleteOpenMessage(Message message, string email)
    {
        string connection = ConfigurationManager.ConnectionStrings["EVENTSConnectionString"].ToString();
        SqlConnection dbConnection = new SqlConnection(connection);
        try
        {
            dbConnection.Open();

            SqlParameter SelectedMessageParam = new SqlParameter("@MESSAGE_ID", System.Data.SqlDbType.Int);
            SelectedMessageParam.Value = Int32.Parse(message.MessageID);

            SqlParameter EmailParam = new SqlParameter("@EMAIL", System.Data.SqlDbType.NVarChar, 50);
            EmailParam.Value = email;

            string deleteMessageCommand = "UPDATE USER_MESSAGE_RECIPIENTS " +
                                          "SET IS_DELETED = 'T' " +
                                          "WHERE MESSAGE_ID = @MESSAGE_ID " +
                                          "AND MESSAGE_RECIPIENT = @EMAIL;";

            SqlCommand deleteMessage = new SqlCommand(null, dbConnection);
            deleteMessage.Parameters.Add(SelectedMessageParam);
            deleteMessage.Parameters.Add(EmailParam);
            deleteMessage.CommandText = deleteMessageCommand;
            deleteMessage.Prepare();
            deleteMessage.ExecuteNonQuery();

            dbConnection.Close();
        }
        catch (SqlException exception)
        {
            //Response.Write("<p> Error Code " + exception.Number + ": " + exception.Message + "</p>");
        }
    }
开发者ID:movies28423,项目名称:Conference-Register,代码行数:33,代码来源:UserHomePage.aspx.cs

示例8: AddFeatureToRole

    public string AddFeatureToRole(SysFeature feature)
    {
        if (!HasFeature(feature))
        {
            string connection = ConfigurationManager.ConnectionStrings["EVENTSConnectionString"].ToString();
            SqlConnection dbConnection = new SqlConnection(connection);
            try
            {
                dbConnection.Open();

                SqlParameter FeatureParam = new SqlParameter("@FEATURE_NAME", System.Data.SqlDbType.NVarChar, 70);
                FeatureParam.Value = feature.FeatureID;
                SqlParameter RoleParam = new SqlParameter("@ROLE_NAME", System.Data.SqlDbType.NVarChar, 70);
                RoleParam.Value = this.roleID;
                SqlParameter TimeStampParam = new SqlParameter("@SYS_TIMESTAMP", System.Data.SqlDbType.NVarChar, 70);
                TimeStampParam.Value = System.DateTime.Now;
                SqlParameter[] AddFeatureParam = new SqlParameter[] { FeatureParam, RoleParam, TimeStampParam };
                string addFeatureCommand = "INSERT INTO ROLE_SET (ROLE_NAME,FEATURE_NAME,SYS_TIMESTAMP) VALUES (@ROLE_NAME, @FEATURE_NAME, @SYS_TIMESTAMP);";
                SqlCommand addFeature = new SqlCommand(null, dbConnection);
                addFeature.Parameters.AddRange(AddFeatureParam);
                addFeature.CommandText = addFeatureCommand;
                addFeature.Prepare();
                addFeature.ExecuteNonQuery();
                dbConnection.Close();
                return feature.FeatureID + " has been added to " + this.roleID;
            }
            catch (SqlException exception)
            {
                return "<p> Error Code " + exception.Number + ": " + exception.Message + "</p>";
            }
        }
        {
            return "Role already has feature";
        }
    }
开发者ID:movies28423,项目名称:Conference-Register,代码行数:35,代码来源:Role.cs

示例9: Main

	static int Main ()
	{
		if (Environment.GetEnvironmentVariable ("MONO_TESTS_SQL") == null)
			return 0;

		using (SqlConnection myConnection = new SqlConnection (CreateConnectionString ())) {
			SqlCommand command = new SqlCommand (drop_stored_procedure, myConnection);
			myConnection.Open ();
			command.ExecuteNonQuery ();

			command = new SqlCommand (create_stored_procedure, myConnection);
			command.ExecuteNonQuery ();

			command = new SqlCommand ("bug316091", myConnection);
			command.CommandType = CommandType.StoredProcedure;
			command.Parameters.Add ("@UserAccountStatus", SqlDbType.SmallInt).Value = UserAccountStatus.ApprovalPending;
			command.Prepare ();
			SqlDataReader dr = command.ExecuteReader ();
			if (!dr.Read ())
				return 1;
			if (dr.GetInt32 (0) != 1)
				return 2;
			if (dr.GetInt32 (1) != 0)
				return 3;
			dr.Close ();

			// clean-up
			command = new SqlCommand (drop_stored_procedure, myConnection);
			command.ExecuteNonQuery ();

			return 0;
		}
	}
开发者ID:mono,项目名称:gert,代码行数:33,代码来源:test.cs

示例10: GetDataReader

 public SqlDataReader GetDataReader(string sql)
 {
     SqlConnection conn = new SqlConnection(ConnectionString);
     conn.Open();
     using (SqlCommand cmd = new SqlCommand(sql, conn))
     {
         cmd.Prepare();
         return cmd.ExecuteReader(CommandBehavior.CloseConnection);
     }
 }
开发者ID:yftiger1981,项目名称:WlnPsyWeb,代码行数:10,代码来源:connectDb.cs

示例11: CommandStored

 public static SqlCommand CommandStored(string query)
 {
     var sqlCo = new SqlCommand
     {
         CommandType = CommandType.StoredProcedure,
         Connection = GetConnection(),
         CommandText = query
     };
     sqlCo.Prepare();
     return sqlCo;
 }
开发者ID:BillyHennin,项目名称:CliniqueVeterinaire,代码行数:11,代码来源:General.cs

示例12: LoginButton_Click

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            try
            {
                var connString = ConfigurationManager.ConnectionStrings["CineQuilla"].ConnectionString;
                using (SqlConnection connection = new SqlConnection(connString))
                {
                    connection.Open();
                    using (SqlCommand command = new SqlCommand(null, connection))
                    {
                        command.CommandText = "SELECT TOP 1 id, username, first_name, last_name, permission_level FROM users WHERE username = @user AND password_hash = HASHBYTES('SHA2_256', @pass)";
                        SqlParameter userParam = new SqlParameter("@user", SqlDbType.VarChar, 255);
                        SqlParameter passParam = new SqlParameter("@pass", SqlDbType.VarChar, 255);

                        userParam.Value = UsernameBox.Text;
                        passParam.Value = PasswordBox.Text;

                        command.Parameters.Add(userParam);
                        command.Parameters.Add(passParam);

                        command.Prepare();
                        var reader = command.ExecuteReader();
                        if (!reader.HasRows)
                        {
                            // There's no matching user
                            LoginError.Visible = true;
                            return;
                        }
                        else
                        {
                            reader.Read();
                            Session["UserInfo"] = new UserInfo
                            {
                                Id = reader.GetInt32(0),
                                Username = reader.GetString(1),
                                FirstName = reader.GetString(2),
                                LastName = reader.GetString(3),
                                PermissionLevel = reader.GetInt32(4)
                            };

                            // Login success!
                            FormsAuthentication.RedirectFromLoginPage(reader.GetInt32(0).ToString(), true);
                        }
                    }
                }
            }
            catch (SqlException ex)
            {
                throw;
            }
        }
开发者ID:Subv,项目名称:CineQuilla,代码行数:54,代码来源:Login.aspx.cs

示例13: update1

 void update1()
 {
     SqlCommand comm = new SqlCommand("insert into tblEmployee(EmployeeName,Sex,Age,DepartmentId) value(@a,'@b',@c,@d)",new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]));
     comm.Connection.Open();
     comm.Prepare();
     comm.Parameters.Add(new SqlParameter("@a","'Ragz'"));
     comm.Parameters.Add(new SqlParameter("@b","M"));
     comm.Parameters.Add(new SqlParameter("@c",23));
     comm.Parameters.Add(new SqlParameter("@d",1));
     comm.ExecuteNonQuery();
     comm.Connection.Close();
 }
开发者ID:rags,项目名称:playground,代码行数:12,代码来源:frmBatchUpdate.aspx.cs

示例14: Button2_Click

        protected void Button2_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            try
            {
                string imgPath = "Uploads" + "/" + ImageUpload.FileName;
                ImageUpload.SaveAs(Server.MapPath("Uploads") + "/" + ImageUpload.FileName);

                var connString = ConfigurationManager.ConnectionStrings["CineQuilla"].ConnectionString;
                using (SqlConnection connection = new SqlConnection(connString))
                {
                    connection.Open();
                    using (SqlCommand command = new SqlCommand(null, connection))
                    {
                        command.CommandText = "INSERT INTO movies (name, description, year, director, length, image) VALUES (@name, @descr, @year, @direc, @len, @img)";
                        SqlParameter nameParam = new SqlParameter("@name", SqlDbType.VarChar, 255);
                        SqlParameter descrParam = new SqlParameter("@descr", SqlDbType.Text, DescriptionBox.Text.Length);
                        SqlParameter yearParam = new SqlParameter("@year", SqlDbType.Int);
                        SqlParameter direcParam = new SqlParameter("@direc", SqlDbType.VarChar, 255);
                        SqlParameter lenParam = new SqlParameter("@len", SqlDbType.Int);
                        SqlParameter imgParam = new SqlParameter("@img", SqlDbType.Text, imgPath.Length);

                        nameParam.Value = NameBox.Text;
                        descrParam.Value = DescriptionBox.Text;
                        yearParam.Value = YearBox.Text;
                        direcParam.Value = DirectorBox.Text;
                        lenParam.Value = LengthBox.Text;
                        imgParam.Value = imgPath;

                        command.Parameters.Add(nameParam);
                        command.Parameters.Add(descrParam);
                        command.Parameters.Add(yearParam);
                        command.Parameters.Add(direcParam);
                        command.Parameters.Add(lenParam);
                        command.Parameters.Add(imgParam);

                        command.Prepare();
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (SqlException ex)
            {
                ErrorLabel.Visible = true;
                return;
            }

            Session["ShowMovieAddedMessage"] = true;
            Response.Redirect(Request.RawUrl);
        }
开发者ID:Subv,项目名称:CineQuilla,代码行数:52,代码来源:ManageMovies.aspx.cs

示例15: TSSqlCommandContainer

        /// <summary>
        /// Constructor.  The constructor will call the Prepare method on the SqlCommand
        /// object, so the caller does not need to call this method.
        /// </summary>
        public TSSqlCommandContainer(int connectionId, SqlConnection sqlConnection, 
                    String tableName, String keyString, SqlCommand sqlCommand)
        {
            ConnectionId = connectionId;
            SqlConnection = sqlConnection;
            TableName = tableName;
            KeyString = keyString;
            SqlCommand = sqlCommand;

            // Prepare the command to ensure that it is cached by the database system.
            // http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/a702d6eb-54bd-492b-9715-59bac182263d/
            SqlCommand.Prepare();
        }
开发者ID:hydrologics,项目名称:TimeSeriesLibrary,代码行数:17,代码来源:TSSqlCommandContainer.cs


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