How to Install/Uninstall/Execute MySQL as Windows Service

On Windows, It is always recommended to install and run MySQL as a Windows service, so that MySQL starts and stops automatically when Windows starts and shutdown. Also, it can be managed using the services section of control panel. A MySQL installed as a service can also be controlled from the command line using NET commands (command to start a service), or with the graphical Services utility. Generally, to install MySQL as a Windows service you should be logged in using an account that has administrator rights.

MySQL

This post is in continuation to series about learning MySQL concepts. In previous post, we learned about MySQL Configuration and Command Line Options. In this post, I will talk about installing and using MySQL as a windows service.

Install MySQL as windows service

To install MySQL as a Windows service manually, execute this in a command line shell, e.g.

prompt> mysqld --install MySQLXY --defaults-file="C:Program FilesMySQLMySQL Server 5.1my.ini"

Where “MySQLXY” is any service name you want to give to MySQL windows service. And “defaults-file” is the location of configuration file which you want to use for providing startup configuration parameters.

Start MySQL as windows service

To Start the installed windows service from command prompt, execute this command e.g.

prompt> net start MySQLXY

Above command will start the service and as a result, MySQL will be running into your system.

Install as a MySQL Windows service manually
Install as a MySQL Windows service manually

Remove/Uninstall MySQL as windows service

To uninstall the installed windows service from command prompt, execute this command e.g.

prompt> sc delete MySQLXY

Above command will delete the windows service. It will not uninstall the MySQL from your system, only windows service gets deleted. NO HARM !!


Need to be done from a command prompt with administrator privileges.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

9 thoughts on “How to Install/Uninstall/Execute MySQL as Windows Service”

  1. Hi Guptha,
    My task is “list of all users who are currently logged into my project”This should pop up as new page on click of a button with name “logged-in users”. The table should list following columns
    1] First Name
    2] Last Name
    3] user-id
    4] email
    5] contact number
    You already send the code but it is not working i’ll send my files could you please check and tell me how to do this ?
    UserPrincipal.java file name
    public final class UserPrincipal //implements Serializable, HttpSessionBindingListener {
    {

    /**
    * User Id.
    */
    private Integer userId;

    /**
    * First Name.
    */
    private String firstName;

    /**
    * Last Name.
    */
    private String lastName;

    /**
    * User Email.
    */
    private String userEmail;

    /**
    * User Email Alias.
    */
    private String userEmailAlias;

    /**
    * Role Code.
    */
    private Integer roleCode;

    /**
    * Change Password Flag.
    */
    private Boolean changePasswordFlag;

    /**
    * Company Name.
    */
    String companyName;

    /**
    * successfull login date time.
    */
    private Date lastSuccessfulLoginTime;

    /**
    * UserPrincipal Constructor.
    *
    * @param userId user id
    * @param firstName first name
    * @param lastName last name
    * @param userEmail user email
    * @param userEmailAlias user email alias
    * @param roleCode role code
    * @param changePasswordFlag change password flag
    * @param companyName user company name
    */
    public UserPrincipal(Integer userId, String firstName, String lastName,
    String userEmail, String userEmailAlias, Integer roleCode,
    Boolean changePasswordFlag, String companyName, Date lastLoginDate) {
    super();
    this.userId = userId;
    this.firstName = firstName;
    this.lastName = lastName;
    this.userEmail = userEmail;
    this.userEmailAlias = userEmailAlias;
    this.roleCode = roleCode;
    this.changePasswordFlag = changePasswordFlag;
    this.companyName = companyName;
    this.lastSuccessfulLoginTime = lastLoginDate;
    }

    /**
    *
    * @return user id
    */
    public Integer getUserId() {
    return userId;
    }

    /**
    *
    * @return first name
    */
    public String getFirstName() {
    return firstName;
    }

    /**
    *
    * @return last name
    */
    public String getLastName() {
    return lastName;
    }

    /**
    *
    * @return user email
    */
    public String getUserEmail() {
    return userEmail;
    }

    /**
    *
    * @return user email alias
    */
    public String getUserEmailAlias() {
    return userEmailAlias;
    }

    /**
    *
    * @return role code
    */
    public Integer getRoleCode() {
    return roleCode;
    }

    /**
    * @return the changePasswordFlag
    */
    public Boolean getChangePasswordFlag() {
    return changePasswordFlag;
    }

    /**
    * @return the companyName
    */
    public String getCompanyName() {
    return companyName;
    }

    /**
    * @return the lastSuccessfulLoginTime
    */
    public Date getLastSuccessfulLoginTime() {
    return lastSuccessfulLoginTime;
    }

    /**
    * @param lastSuccessfulLoginTime the lastSuccessfulLoginTime to set
    */
    public void setLastSuccessfulLoginTime(Date lastSuccessfulLoginTime) {
    this.lastSuccessfulLoginTime = lastSuccessfulLoginTime;
    }

    /**
    * This method throw CloneNotSupportedException, whenever anyone try to
    * attempt cloning operation.
    *
    * @see java.lang.Object#clone()
    * @return Object
    * @throws CloneNotSupportedException clone not supported
    */
    @Override
    protected Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
    }

    /* (non-Javadoc)
    * @see javax.servlet.http.HttpSessionBindingListener#valueBound(javax.servlet.http.HttpSessionBindingEvent)
    */
    /* @SuppressWarnings(“unchecked”)
    @Override
    public void valueBound(HttpSessionBindingEvent sessionBindingEvent) {
    System.out.println(“in valueBound===================================================================================”);

    System.out.println(” added userPrinipal “);
    ServletContext appContext = sessionBindingEvent.getSession()
    .getServletContext();
    Map loggedInUsersMap = new HashMap();

    if (appContext.getAttribute(“loggedInUsersMap”) == null) {

    appContext.setAttribute(“loggedInUsersMap”, loggedInUsersMap);
    } else {
    loggedInUsersMap = (Map) appContext
    .getAttribute(“loggedInUsersMap”);
    }
    UserPrincipal userPrincipal = (UserPrincipal) sessionBindingEvent
    .getSession().getAttribute(“userPrincipal”);

    // add loggedin user into map
    if(userPrincipal != null)
    loggedInUsersMap.put(userPrincipal.getUserId(), userPrincipal);

    }

    (non-Javadoc)
    * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(javax.servlet.http.HttpSessionBindingEvent)

    @SuppressWarnings(“unchecked”)
    @Override
    public void valueUnbound(HttpSessionBindingEvent sessionBindingEvent) {
    System.out.println(“in valueUnbound===================================================================================”);

    // TODO Auto-generated method stub
    System.out.println(” remove userPrinipal “);
    ServletContext appContext = sessionBindingEvent.getSession()
    .getServletContext();
    Map loggedInUsersMap = new HashMap();

    if (appContext.getAttribute(“loggedInUsersMap”) == null) {

    appContext.setAttribute(“loggedInUsersMap”, loggedInUsersMap);
    } else {
    loggedInUsersMap = (Map) appContext
    .getAttribute(“loggedInUsersMap”);
    }
    UserPrincipal userPrincipal = (UserPrincipal) sessionBindingEvent
    .getSession().getAttribute(“userPrincipal”);

    // add loggedin user into map
    if(userPrincipal != null)
    loggedInUsersMap.remove(userPrincipal.getUserId());

    }*/

    /**
    * @return
    */

    }
    UserController.java:this file specifies the connection form server to UI

    // @SuppressWarnings({ “unused”, “unchecked” })
    @RequestMapping(“/getLoggedInUser”)
    public @ResponseBody String getUserDetails(HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {
    //logger.trace(“Entering method”);
    // Get the session object
    //HttpSession session = null;
    //session = request.getSession(false);
    JSONObject outerObj = new JSONObject();
    JSONArray userArray = new JSONArray();
    List userlist = new ArrayList();
    userlist.add(new UserPrincipal(1, “gfgf”, “gfgfdg”, “gfgfdg”, “gfgfdg”, 2, false, “gfgfdg”, new Date()));
    userlist.add(new UserPrincipal(2, “gfgf”, “gfgfdg”, “gfgfdg”, “gfgfdg”, 2, false, “gfgfdg”, new Date()));
    userlist.add(new UserPrincipal(3, “gfgf”, “gfgfdg”, “gfgfdg”, “gfgfdg”, 2, false, “gfgfdg”, new Date()));
    userlist.add(new UserPrincipal(4, “gfgf”, “gfgfdg”, “gfgfdg”, “gfgfdg”, 2, false, “gfgfdg”, new Date()));

    UserPrincipal user = null;
    //JSONObject User = new JSONObject();
    for (UserPrincipal user1 :userlist ) {
    JSONObject userObj = new JSONObject();
    userObj.put(“userId”, user1.getUserId());
    userObj.put(“userFirstName”, user1.getFirstName());
    userObj.put(“userLastName”, user1.getLastName());
    userObj.put(“userEmail”, user1.getUserEmail());
    //userObj.put(“userPhone”, user1.getUserPhone());
    userObj.put(“userCompanyNname”, user1.getCompanyName());
    userArray.add(userObj);

    }

    outerObj.put(“Result”, “OK”);
    outerObj.put(“Records”, userArray);
    outerObj.put(“TotalRecordCount”, userArray.size());

    logger.debug(“getUserDetails method”);
    return outerObj.toJSONString();
    }
    and this is my jtable mange.js
    var jTable;
    function showLoggedInUsers() {

    // start of logged in user jTable.
    updateBackgroundHeight();
    $(“#LoggedInUserTableContainer”).jtable({
    title:’Logged-In Users’,
    paging: true, //Enable paging
    pageSize: 10, //Set page size
    sorting: true, //Enable sorting
    //width:700,
    defaultSorting: ‘userId ASC’, //Set default sorting
    listClass: ‘child-opener-image-column’,
    openChildAsAccordion: true,
    jqueryuiTheme :true,
    recordsLoaded: onRecordsLoaded,
    loadingAnimationDelay : 0,
    ajaxSettings: {
    type: ‘POST’,
    dataType: ‘json’
    },
    actions: {
    listAction: ‘getLoggedInUser’
    }, //end of actions

    messages : {
    noDataAvailable : jQuery.i18n.prop(‘userManagement.jtable.noRecords’),
    loadingMessage : “wait..Loading data”
    },

    fields: {
    userId: {
    key: true,
    //title: jQuery.i18n.prop(‘userManagement.jtable.lblUserId’),
    create: true,
    edit: true,
    list: false
    },

    userFirstName: {
    //title: jQuery.i18n.prop(‘userManagement.jtable.lblFirstName’),
    create: true,
    edit: true,
    list: true,
    width:’14%’
    },
    userLastName: {
    //title: jQuery.i18n.prop(‘userManagement.jtable.lblLastName’),
    create: true,
    edit: true,
    list: true,
    width:’14%’
    },
    userCompanyNname: {
    //title: jQuery.i18n.prop(‘userManagement.jtable.lblCompany’),
    create: true,
    edit: true,
    list: true,
    width:’11%’
    },
    userPhone: {
    //title: jQuery.i18n.prop(‘userManagement.jtable.lblPhoneNo’),
    create: true,
    edit: true,
    list: true,
    width:’19%’
    },
    userEmail: {
    //title: jQuery.i18n.prop(‘userManagement.jtable.lblEmail’),
    create: true,
    edit: true,
    list: true,
    width:’14%’
    },
    }
    });

    //end of jtable
    //showActionDialog(jTable, “Logged-In Users”);
    //showLoader(“Wait. Loading User Data…”);
    $(‘#LoggedInUserTableContainer’).jtable(‘load’);
    }

    Reply
  2. Hi Guptha,
    I had a doubt.My doubt is there is one login screen,after login screen there is one user management page.In UM page there is one jtable is displayed.So my question is there is one “logged in users” button in toolbar.In table i already predefined some users with the fields of (First name,Last-name,Company,phone-no).when i click that button i have to show logged in users list.How to do this task in session could you please help me in this…?

    Reply
    • Just collect all logged in users in a Set in the application scope. Let’s implement HttpSessionBindingListener and add/remove the user from the Set when it’s about to be bound/unbound in the session.

      public class User implements HttpSessionBindingListener {

      @Override
      public void valueBound(HttpSessionBindingEvent event) {
      Set logins = (Set) event.getSession().getServletContext().getAttribute("logins");
      logins.add(this);
      }

      @Override
      public void valueUnbound(HttpSessionBindingEvent event) {
      Set logins = (Set) event.getSession().getServletContext().getAttribute("logins");
      logins.remove(this);
      }

      // @Override equals() and hashCode() as well!

      }

      Then, anywhere in your application where you’ve access to the ServletContext, like in a servlet, you can just access the logged-in users as follows:

      Set logins = (Set) getServletContext().getAttribute("logins");

      Reply
  3. Since deleting the service wont uninstall MySQL, can we not manually configure MYSqlXY service to not start when windows start ,so that we need not create service again?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.