Tampilkan postingan dengan label Database. Tampilkan semua postingan
Tampilkan postingan dengan label Database. Tampilkan semua postingan

How To Check MySQL Was Running With Python Script

How To Check MySQL Was Running With Python Script
Sering pertanyaan kita hinggap dipikiran kita, semakin dipikirkan semakin gak ngerti seringnya, apalagi sesuatu yang gak kliatan kerjanya seperti master kita satu ini MySQL Database. Awalnya ini script digunakan untuk keperluan deteksi pakah mysql jalan atao kagak, Kalo mysqlnya gak jalan tinggal dikasih script buat jalanin si doi, jadi kalo misalnya ada aplikasi yang mau masukin n baca data tinggal cek dulu apa mysql ini jalan ato kagak. 

Aplikasi yang baru dikembangin kebetulan pake python n jalan di Raspberry Pi Rev B, dan rencanya ini nanti dikasih di crontab nya cron buat di cek setiap menit untuk memastikan database jalan dengan sempurna, karena ane juga gak ngerti script python mungkin sering juga gua browse sana sini, eee gua nemu juga di internet script ajaib ini.

Manfaatin subprocess yang ada di Python langsung memberikan perintah melalui shell/terminal. Di raspberry penggunaan perintah ini gak perlu pake memasukkan pasword dari sudo yang dilakukan kalo memang dibutuhkan untuk menjalakn proses dengan authorisasi Super user.

Cara paling mudah untuk membuat ini bekerja adalah sebagai berikut

Script :

import subprocess
import string

msqlr = subprocess.Popen("sudo /usr/sbin/netstat -al".split(), stdout=subprocess.PIPE).stdout
grep = subprocess.Popen(["/usr/bin/grep", "mysql"], stdin=msqlr, stdout=subprocess.PIPE).stdout
msqlrLines = grep.read().split("\n")
vals = map(string.strip, msqlrLines[0].split())
print vals
if vals[-1] in ("LISTENING", "LISTEN"):
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."


Yang dibawah ini mungkin agak berbeda, kalo kalian ingin mereset MySQL jalankan peritah berikut dengan cript python :

Shell script to restart MySQL server if it is killed or not workin

    #!/bin/bash # Shell script to restart MySQL server if it is killed or not working # due to ANY causes. # When script detects mysql is not running (it basically sends ping request # to MySQL) it try to start using /etc/init.d/mysql script; and it sends an # email to user indicating the status. # This script must be run from Cron Job so that it can monitor mysql server. # For more info visit following url: # http://www.cyberciti.biz/nixcraft/vivek/blogger/2005/08/linux-mysql-server-monitoring.html # -------------------------------------------------------------------------- # Copyright (C) 2005 nixCraft project # This script is licensed under GNU GPL version 2.0 or above # ------------------------------------------------------------------------- # This script is part of nixCraft shell script collection (NSSC) # Visit http://bash.cyberciti.biz/ for more information. # ------------------------------------------------------------------------- # mysql root/admin username MUSER="root" # mysql admin/root password MPASS="SET-ROOT-PASSWORD" # mysql server hostname MHOST="localhost" #Shell script to start MySQL server i.e. path to MySQL daemon start/stop script. # Debain uses following script, need to setup this according to your UNIX/Linux/BSD OS. MSTART="/etc/init.d/mysql start" # Email ID to send notification EMAILID="notification@somewhere-corp.com" # path to mail program MAILCMD="$(which mail)" # path mysqladmin MADMIN="$(which mysqladmin)" #### DO NOT CHANGE anything BELOW #### MAILMESSAGE="/tmp/mysql.fail.$$" # see if MySQL server is alive or not # 2&1 could be better but i would like to keep it simple and easy to # understand stuff :) $MADMIN -h $MHOST -u $MUSER -p${MPASS} ping 2>/dev/null 1>/dev/null if [ $? -ne 0 ]; then echo "" >$MAILMESSAGE echo "Error: MySQL Server is not running/responding ping request">>$MAILMESSAGE echo "Hostname: $(hostname)" >>$MAILMESSAGE echo "Date & Time: $(date)" >>$MAILMESSAGE # try to start mysql $MSTART>/dev/null # see if it is started or not o=$(ps cax | grep -c ' mysqld$') if [ $o -eq 1 ]; then sMess="MySQL Server MySQL server successfully restarted" else sMess="MySQL server FAILED to restart" fi # Email status too echo "Current Status: $sMess" >>$MAILMESSAGE echo "" >>$MAILMESSAGE echo "*** This email generated by $(basename $0) shell script ***" >>$MAILMESSAGE echo "*** Please don't reply this email, this is just notification email ***" >>$MAILMESSAGE # send email $MAILCMD -s "MySQL server" $EMAILID < $MAILMESSAGE else # MySQL is running :) and do nothing : fi # remove file rm -f $MAILMESSAGE
Sekian cerita ane ntar nyambung lagi...

Allowing SQL Server Connection From Network

Allowing SQL Server Connection From Network
Upon database modeling with the ORM feature, you always need to connect to the server. However, you may encounter problem in connecting to the SQL server, which is great obstruction to your modeling. In this article, we will provide ways to help you to check whether your configurations for connecting to SQL Server are correct.
There are three significant aspects that uses may neglect, leading the failure of the connection to the SQL Server.

Server Settings

Enable TCP/IP

  1. Open your SQL Server Configuration Manager.
    open sql config manager
  2. Expand SQL Server Network Configuration and select Protocols for SQLEXPRESS.
    sql network config express
  3. Take a look at TCP/IP, which requires to be Enabled. If yours is Disabled, right-click on it and select Enable in the popup menu.
    enable tcp ip
  4. Also, you may take a look at the Port setting of your server. Right-click on TCP/IP and select Properties in the popup menu.
    right click tcp ip properties
  5. Click the IP Address tab in the TCP/IP Properties dialog box.
    click ip address tab
  6. Under IPAll section, you can see the TCP Port (default: 1433) and you can edit the port of your server.
    tcp port

Correct Hostname and Port

Back to your VP application, have a check in your database configuration and see if you have entered the Hostname and Port correctly.
  1. Select Tools > Object-Relational Mapping (ORM) > Database Configuration in the VP application.
    tool orm db config
  2. Select the Language, server and the driver in the Database Configuration dialog box.
    select lang server driver
  3. Enter Hostname, which must be either the IP address of your computer or your computer name.
    db config hostname
  4. Enter the port of your SQL Server. It's 1433 by default, but if you have edited the port for your SQL Server or running on other named instance, you need to enter the corresponding port.
    db config port

Allow Remote Connection

Your need to make sure that remote connection to your SQL Server is enabled.
  1. Startup your SQL Server.
    start sql server
  2. Right-click on the server and select Properties in the popup menu.
    right click sql server properties
  3. In the Server Properties dialog box, select Connections.
    select connection
  4. Check the checkbox of Allow remote connections to this server.
    check allow remote connection

Diagnosis of Connection in Command Line

You can diagnose whether your SQL Server is in-use by the command line. For Windows Vista, Telnet is not installed by default, you need to install it before running the telnet command.

Install Telnet Client in Windows Vista

  1. Open Control Panel from the Start Menu.
    control panel
  2. Select Programs in the Control Panel.
    select programs
  3. Under Programs and Features, select Turn Windows features on or off.
    select turn on off win features
  4. Scroll down to find the option Telnet Client, check this option and press OK.
    select telnet client

Run Telnet Command

  1. Shutdown your SQL Server first and launch the command prompt.
  2. Enter telnet %host% %port% in the command prompt, where %host% and %port% are the host and port of your SQL Server.
    enter telnet msg in command
  3. Press Enter to see if it can call the SQL Server. If telnet can communicate with the host and port you specified, it will show a blank dialog box. This means your SQL Server is able to be connected.
    telnet succeed connect to sql
    If it fails to connect to your SQL Server, there will be message of the failure.
    telnet cannot connect to sql

Authentication Method

Make sure that you are using the appropriate authentication method in connecting to your SQL Server.
  1. Startup your SQL Server.
    start sql server
  2. Right-click on the server and select Properties in the popup menu.
    right click sql server properties
  3. In the Server Properties dialog box, select Security.
    select security
  4. Normally, the Server Authentication is set to SQL Server and Windows Authentication Method.
    select sql and win auth
  5. If you are using the Windows Authentication Method, you will need another connection URL in order to connect to the SQL Server.
    • Java (SQL Server 2005 Microsoft Driver)
      jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true;
    • Java (jDTS)
      jdbc:jtds:://[:][/];domain=XXX
      where = sqlserver
      ** Domain Server is required. If no domain server is available, please try domain=workgroup
    • .NET:
      Server=%HOST%,%PORT%;Database=%DATABASE%;User ID=%USER_ID%;Password=%PASSWD%;Trusted_Connection=Yes;Domain=%WINDOW_DOMAIN%
  6. Get back to the VP application and enter the URL in the Connection String section in the Database Configuration dialog box.
    enter url in connection string

Adapter File

While you are using can non-compatible adapter file, you will not be able to connect to the server.
The simplest way to get the compatible adapter file is let our application download it for you:
  1. Select Tools > Object-Relational Mapping (ORM) > Database Configuration.
    tool orm db config
  2. After you have chosen the language, server and driver, click the Download and Update button beside the Adapter file field.
    dl adapter file
  3. VP will download the adapter file for you.
    adapter file downloaded
If your still fail to connect to SQL server with all the above steps of checking, please contact support-team@visual-paradigm.com for technical suppot.

Seven Deadly Sins of Database Design

Seven Deadly Sins of Database Design

How to avoid the worst problems in database design.
by Jason Tiret

Several factors can lead to a poor database design -- lack of experience, a shortage of the necessary skills, tight timelines and insufficient resources can all contribute. In turn, poor database design leads to many problems down the line, such as sub-par performance, the inability to make changes to accommodate new features, and low-quality data that can cost both time and money as the application evolves.
I constantly hear from data professionals that if you don’t get the data right, nothing else matters. However, many times it is the tail (i.e., the application) that’s wagging the dog rather than the dog wagging the tail. The database just comes along for the ride as the application grows in scope and functionality.
Addressing some simple data modeling and design fundamentals can greatly alleviate most, if not all, of these concerns. In this article we’ll focus on seven common database design “sins” that can be easily avoided and suggest ways to correct them in future projects:
  1. Poor or missing documentation for database(s) in production
  2. Little or no normalization
  3. Not treating the data model like a living, breathing organism
  4. Improper storage of reference data
  5. Not using foreign keys or check constraints
  6. Not using domains and naming standards
  7. Not choosing primary keys properly

Sin #1: Poor or missing documentation for database(s) in production

Documentation for databases usually falls into three categories: incomplete, inaccurate, or none at all. To make matters worse, it is almost never centralized in one place. Without proper, centralized documentation, understanding the impact of a change is difficult at best, impossible at worst. This causes developers, DBAs, architects, and business analysts to scramble to get on the same page. They are left up to their own imagination to interpret the meaning and usage of the data.
Additionally, developers may think that the table and column names are descriptive or self explanatory enough to understand the usage of the data (more on this with Sin #6). However, as the workforce turns over, if there is no documentation in place, knowledge of the systems can literally walk out the door leaving a huge void that is impossible to fill. Even starting bottom-up with just the physical information can alleviate the issue of lack of documentation tremendously.
The best approach is to place the models into a central repository and spawn automated reports because despite minimal effort everyone benefits. Producing a central store of models is only half the battle, though. Once that is done, executing validation and quality metrics will enhance the quality of the models over time. As your level of governance increases, you can extend what metadata is captured in the models.

Sin #2: Little or no normalization

There are times to denormalize a database structure to achieve optimized performance, but sacrificing flexibility will paint you in a corner. Despite the long-held belief by developers, one table to store everything is not always optimal. The “one table” approach may make data access easier, but invariably there will be many NULLs for columns that do not apply to a record, and special application code will be needed to handle it. Another common mistake is repeating values stored in a table. This can greatly decrease flexibility and increase difficulty when updating the data.
Understanding even the basics of normalization adds flexibility to a design while reducing redundant data. The first three levels of normalization are usually sufficient for most cases:
  • First Normal Form: Eliminate duplicate columns and repeating values in columns
  • Second Normal Form: Remove redundant data that apply to multiple columns
  • Third Normal Form: Each column of a table should be dependent on the primary identifier


Figure 1: Denormalized structure

Figure 2: Normalized equivalent
The first normal form tells us to break off Address and Phone information into their own tables with identifiers. Following the second normal form, we break off Zip Code information into its own table so that it is not duplicated for each address. Consideration should be made for City and State information as well, but that might be a case where performance over duplication wins. Third normal form would have us look at Organization Name and Industry in the Customer table and put those into their own tables since they are not functionally dependent on the Customer ID. The same would apply to City and State Code in the ZIP Code table.

Sin #3: Not treating the data model like a living, breathing organism

I have seen numerous examples of customers performing the modeling up front, but once the design is in production, all modeling ceases. It is always preferable to design first then build. It is proven that errors corrected in the design phase are significantly less costly than those fixed after production.
The sin arises when changes creep into the database due to critical production issues. Inevitably, the model is then left languishing on the side if there is not a process to update the model along with the database. As more changes occur in the database, the model becomes useless.
Undocumented data can also lead to security and compliance risks, poor understanding of future changes and the inability to adapt to future needs of the business. Although the design-then-build practice may be a utopia that is never reached, the changes need to find their way back to the model.

Sin #4: Improper storage of reference data

I see two main problems with reference data. It is either stored in many places or, even worse, embedded in the application code. It is almost never captured in the data model with the rest of the documentation. This causes huge problems when a reference value needs to change. Reference values provide valuable documentation which should be communicated. Your best chance is often via the model. It may not be practical to store reference values in the data model if you have large volumes, but there is no excuse not to point to them from the model. The key is to have it defined in one place and used in other places. 

 Sin #5: Not using foreign keys or check constraints

I hear customers complain all the time about the lack of referential integrity (RI) or validation checks defined in the database when reverse engineering databases. For older database systems, it was thought that foreign keys and check constraints slowed performance, thus, the RI and checks should be done via the application. This might have been the case in the past, but DBMSs have come a long way. 
 The ramifications on data quality if the data is not validated properly by the application or by the database can be substantial. If it is possible to validate the data in the database, you are better off doing it there. Error handling will be drastically simplified and data quality will increase as a result. 

 Sin #6: Not using domains and naming standards

Domains and naming standards are probably two of the most important things you can incorporate into your modeling practices. Domains allow you to create reusable attributes so that the same attributes are not created in different places with different properties. It is extremely important to have a common set that everyone can use across all models. Naming standards allow you to clearly identify those attributes consistently.
Having a set of standards also ensures consistency across systems and promotes readability of models and code. You don’t want short, cryptic names that users need to interpret. Given the advanced nature of the latest vendor releases, the days of limited column length name are over when building new databases. Always have a common set of classwords to identify key types of data and use modifiers as needed. 

 Sin #7: Not choosing primary keys properly

I was once told by a senior data architect that “When choosing a primary key, you’d better get it right because changing it down the line will be a royal pain.” Sure enough, later I worked with a different customer who had the un-enviable chore of managing a migration project because a system used Social Security number as a primary key for individuals. They found out the hard way that SSNs are not always unique and not everyone has one.
The simplest principle to remember when picking a primary key is SUM: Static, Unique, Minimal. It is not necessary to delve into the whole natural vs. surrogate key debate; however, it is important to know that although surrogate keys may uniquely indentify therecord, they do not always unique identify the data. There is a time and a place for both, and you can always create an alternate key for natural keys if a surrogate is used as the primary key. 
Jason Tiret is the director of product management for modeling and design solutions for Embarcadero (www.embarcadero.com), a provider of multi-platform database tools and developer software.