Jaslabs: High performance Software

High Performance Software

Archive for the 'mysql' Category

using java and mysql

by Paul DuBois

You can write MySQL applications in a variety of languages. The languages that most people use with MySQL are PHP and Perl, but a sometimes overlooked option is the MySQL Connector/J driver, which allows you to develop Java applications that interact with your MySQL server.
MySQL Connector/J works within the framework of the Java JDBC interface, an API that allows Java programs to use database servers in a portable way. JDBC is based on an approach similar to that used in the design of Perl and Ruby DBI modules, Python’s DB-API module, and

PHP’s PEAR::DB class. This approach uses a two-tier architecture:
The top level is visible to application programs and presents an abstract interface for connecting to and using database engines. The application interface does not depend on details specific to particular engines.

The lower level consists of drivers for individual database engines. Each driver handles the details necessary to map the abstract application interface onto operations that a specific engine will understand.The JDBC interface allows developers to write applications that can be used with different databases with a minimum of porting effort. Once a driver for a given server engine is installed, JDBC applications can communicate with any server of that type. By using MySQL Connector/J, your Java programs can access MySQL databases.

Note: MySQL Connector/J is the successor to the MM.MySQL driver. If you have JDBC programs written for MM.MySQL, they should work with MySQL Connector/J as well, although you may want to update the driver class name used in your programs. Just replace instances of org.gjt.mm.mysql in your Java source files with com.mysql.jdbc and recompile.

Preliminary Requirements

To use Java applications with MySQL, you may need to install some additional software:
If you want to compile and run Java programs, you’ll need a Java compiler (such as javac or jikes) and a runtime environment. If these are not already installed on your system, you can get them by obtaining a Java Software Development Kit (SDK) from java.sun.com.

If you want only to run precompiled applications, no compiler is necessary, but you’ll still need a Java Runtime Environment (JRE). This too may be obtained from java.sun.com.This article assumes that you’ll write and compile your own programs, and thus that you have a Java SDK installed. Once you compile a Java program, however, you can deploy it to other machines, even ones that have only a runtime environment. This works even in heterogenous installations, because Java is platform-independent. Applications compiled on one platform can be expected to work on other platforms. For example, you can develop on a Linux box and deploy on Windows

Connecting to the MySQL Server

To connect to the MySQL server, register the JDBC driver you plan to use, then invoke its getConnection() method. The following short program, Connect.java, shows how to connect to and disconnect from a server running on the local host. It accesses a database named test, using a MySQL account with a user name and password of testuser and testpass: import java.sql.*;

public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = “testuser”;
String password = “testpass”;
String url = “jdbc:mysql://localhost/test”;
Class.forName (”com.mysql.jdbc.Driver”).newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println (”Database connection established”);
}
catch (Exception e)
{
System.err.println (”Cannot connect to database server”);
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println (”Database connection terminated”);
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}

Compile Connect.java to produce a class file Connect.class that contains executable Java code: % javac Connect.java
Then invoke the class file as follows and it should connect to and disconnect from your MySQL server: % java Connect
Database connection established
Database connection terminated
If you have trouble compiling Connect.java, double check that you have a Java Software Development Kit installed and make sure that the MySQL Connector/J driver is listed in your CLASSPATH environment variable.

The arguments to getConnection() are the connection URL and the user name and password of
a MySQL account. As illustrated by Connect.java, JDBC URLs for MySQL consist of jdbc:mysql:// followed by the name of the MySQL server host and the database name. An alternate syntax for specifying the user and password is to add them as parameters to the end of the connection URL: jdbc:mysql://localhost/test?user=testuser&password=testpass
When you specify a URL using this second format, getConnection() requires only one argument.

For example, the code for connecting to the MySQL server in Connect.java could have been written like this: String userName = “testuser”;
String password = “testpass”;
String url = “jdbc:mysql://localhost/test?user=”
+ userName
+ “&password=”
+ password;
Class.forName (”com.mysql.jdbc.Driver”).newInstance ();
conn = DriverManager.getConnection (url);

getConnect() returns a Connection object that may be used to interact with MySQL by issuing queries and retrieving their results. (The next section describes how to do this.) When you’re done with the connection, invoke its close() method to disconnect from the MySQL server.

To increase the portability of your applications, you can store the connection parameters (host, database, user name, and password) in a Java properties file and read the properties at runtime. Then they need not be listed in the program itself. This allows you to change the server to which the program connects by editing the properties file, rather than by having to recompile the program.

Issuing Queries

To process SQL statements in a JDBC-based application, create a Statement object from your Connection object. Statement objects support an executeUpdate() method for issuing queries that modify the database and return no result set, and an executeQuery() method for queries that do return a result set. The query-processing examples in this article use the following table, animal, which contains an integer id column and two string columns, name and category: CREATE TABLE animal
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
name CHAR(40),
category CHAR(40)
)
id is an AUTO_INCREMENT column, so MySQL automatically assigns successive values 1, 2, 3, … as records are added to the table.
Issuing Queries That Return No Result Set
The following example obtains a Statement object from the Connection object, then uses it to create and populate the animal table. DROP TABLE, CREATE TABLE, and INSERT all are statements that modify the database, so executeUpdate() is the appropriate method for issuing them:

Statement s = conn.createStatement ();
int count;
s.executeUpdate (”DROP TABLE IF EXISTS animal”);
s.executeUpdate (
“CREATE TABLE animal (”
+ “id INT UNSIGNED NOT NULL AUTO_INCREMENT,”
+ “PRIMARY KEY (id),”
+ “name CHAR(40), category CHAR(40))”);
count = s.executeUpdate (
“INSERT INTO animal (name, category)”
+ ” VALUES”
+ “(’snake’, ‘reptile’),”
+ “(’frog’, ‘amphibian’),”
+ “(’tuna’, ‘fish’),”
+ “(’racoon’, ‘mammal’)”);
s.close ();
System.out.println (count + ” rows were inserted”);
The executeUpdate() method returns the number of rows affected by a query. As shown above, the count is used to report how many rows the INSERT statement added to the animal table.

A Statement object may be used to issue several queries. When you’re done with it, invoke its close() method to dispose of the object and free any resources associated with it

Issuing Queries That Return a Result Set

For statements such as SELECT queries that retrieve information from the database, use executeQuery(). After calling this method, create a ResultSet object and use it to iterate through the rows returned by your query. The following example shows one way to retrieve the contents of the animal table:

Statement s = conn.createStatement ();
s.executeQuery (”SELECT id, name, category FROM animal”);
ResultSet rs = s.getResultSet ();

int count = 0;
while (rs.next ())
{
int idVal = rs.getInt (”id”);
String nameVal = rs.getString (”name”);
String catVal = rs.getString (”category”);
System.out.println (
“id = ” + idVal
+ “, name = ” + nameVal
+ “, category = ” + catVal);
++count;
}
rs.close ();
s.close ();

System.out.println (count + ” rows were retrieved”);

executeQuery() does not return a row count, so if you want to know how many rows a result set contains, you should count them yourself as you fetch them.
To obtain the column values from each row, invoke getXXX() methods that match the column data types. The getInt() and getString() methods used in the preceding example return integer and string values. As the example shows, these methods may be called using the name of a result set column. You can also fetch values by position. For the result set retrieved by the SELECT query in the example, id, name, and category are at column positions 1, 2 and 3 and thus could have been obtained like this:

int idVal = rs.getInt (1);
String nameVal = rs.getString (2);
String catVal = rs.getString (3);

ResultSet objects, like Statement objects, should be closed when you’re done with them.

To check whether or not a column value is NULL, invoke the result set object’s wasNull() method after fetching the value. For example, you could check for a NULL value in the name column like this: String nameVal = rs.getString (”name”);

if (rs.wasNull ())
nameVal = “(no name available)”;

Using Placeholders

Sometimes it’s necessary to construct queries from values containing characters that require special treatment. For example, in queries, string values are written enclosed within quotes, but any quote characters in the string itself should be doubled or escaped with a backslash to avoid creating malformed SQL. In this case, it’s much easier to let JDBC handle the escaping for you, rather than fooling around trying to do so yourself. To use this approach, create a different kind of statement (a PreparedStatement), and refer to the data values in the query string by means of placeholder characters. Then tell JDBC to bind the data values to the placeholders and it will handle any special characters automatically.

Suppose you have two variables nameVal and catVal from which you want to create a new record in the animal table. To do so without regard to whether or not the values contain special characters, issue the query like this:

PreparedStatement s;
s = conn.prepareStatement (
“INSERT INTO animal (name, category) VALUES(?,?)”);
s.setString (1, nameVal);
s.setString (2, catVal);
int count = s.executeUpdate ();
s.close ();

System.out.println (count + ” rows were inserted”);
The ‘?’ characters in the query string act as placeholders–special markers indicating where data values should be placed. The setString() method takes a placeholder position and a string value and binds the value to the appropriate placeholder, performing any special-character escaping that may be necessary. The method you use to bind a value depends on the data type. For example, setString() binds string values and setInt() binds integer values.

Error Handling

If you want to trap errors, execute your JDBC operations within a try block and use an exception handler to display information about the cause of any problems that occur. JDBC provides getMessage() and getErrorCode() methods that may be invoked when an exception occurs to obtain the error message and the numeric error code. The following example deliberately issues a malformed query. When it runs, the executeQuery() method fails and raises an exception that is handled in the catch block: try
{
Statement s = conn.createStatement ();
s.executeQuery (”XYZ”); // issue invalid query
s.close ();
}
catch (SQLException e)
{
System.err.println (”Error message: ” + e.getMessage ());
System.err.println (”Error number: ” + e.getErrorCode ());
}

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
1 comment

ezsql 2.0 released

Overview

ezSQL is a class that makes it ridiculously easy to use mySQL, Oracle8, SQLite (PHP), within your PHP script. Includes lots of examples making it very easy to understand how to work with databases. ezSQL has excellent debug functions making it lightning-fast to see what’s going on in your SQL code. ezSQL can dramatically decrease development time and in most cases will streamline your code and make things run faster.
Features

ezSQL is a widget that makes it ridiculously easy for you to use mySQL, Oracle8, InterBase/FireBird, PostgreSQL, SQLite (PHP), SQLite (C++) or MS-SQL database(s) within your PHP/C++ scripts (more db’s coming soon)

It is one php file that you include at the top of your script. Then, instead of using standard php database functions listed in the php manual, you use a much smaller (and easier) set of ezSQL functions.

It automatically caches query results and allows you to use easy to understand functions to manipulate and extract them without causing extra server overhead

It has excellent debug functions making it lightning-fast to see what’s going on in your SQL code

Most ezSQL functions can return results as Objects, Associative Arrays, or Numerical Arrays

It can dramatically decrease development time and in most cases will streamline your code and make things run faster as well as making it very easy to debug and optimise your database queries.

Works with Smarty templating language

It is a small class and will not add very much overhead to your website.

Download ezSQL completely Free from here , also check out EZ Results Paging Class ezSQL’s sister class that makes result paging a snip.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
No comments

Mysql: Client Does not support authentication protocol

Introduction

If you have ever gotten the error “Client does not support authentication protocol” when trying to use php or any other language to connect to a mysql server, there is a simple method to fix it.

Why Does this happen?

MySQL 5.0 uses an authentication protocol based on a password hashing algorithm that is incompatible with that used by older (pre-4.1) clients. If you upgrade the server from 4.1, attempts to connect to it with an older client may fail with the following message:
shell> mysql
Client does not support authentication protocol requested by server; consider upgrading MySQL client

Solution

To solve this problem, the following has been the easiest and most effective

SET PASSWORD FOR
-> ’some_user’@’some_host’ = OLD_PASSWORD(’newpwd’);
Alternatively, use UPDATE and FLUSH PRIVILEGES: mysql> UPDATE mysql.user SET Password = OLD_PASSWORD(’newpwd’)
-> WHERE Host = ’some_host’ AND User = ’some_user’;
mysql> FLUSH PRIVILEGES;

Substitute the password you want to use for “newpwd” in the preceding examples. MySQL cannot tell you what the original password was, so you’ll need to pick a new one.
Tell the server to use the older password hashing algorithm:

For each account record displayed by the query, use the Host and User values and assign a password using the OLD_PASSWORD() function and either SET PASSWORD or UPDATE, as described earlier.

Note: In older versions of PHP, the mysql extension does not support the authentication protocol in MySQL 4.1.1 and higher. This is true regardless of the PHP version being used. If you wish to use the mysql extension with MySQL 4.1 or newer, you may need to follow one of the options discussed above for configuring MySQL to work with old clients. The mysqli extension (stands for “MySQL, Improved”; added in PHP 5) is compatible with the improved password hashing employed in MySQL 4.1 and higher, and no special configuration of MySQL need be done in order to use this MySQL client library. For more information about the mysqli extension, see http://php.net/mysqli.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
No comments

mysql or microsoft sql?

(originally from mssqlcity.com)

Introduction

Often people in newsgroups ask about some comparison of Microsoft SQL Server and MySQL. In this article, I compare SQL Server 2000 with MySQL version 4.1 regarding price, performance, platforms supported, SQL dialects and products limits.

Platform comparison

SQL Server 2000 only works on Windows-based platforms, including Windows 9x, Windows NT, Windows 2000 and Windows CE.In comparison with SQL Server 2000, MySQL version 4.1 supports all known platforms, including Windows-based platforms, AIX-based systems, HP-UX systems, Linux Intel, Sun Solaris and so on.

Hardware requirements

To install SQL Server 2000, you should have the Intel or compatible platforms and the following hardware:

Processor: Pentium 166 MHz or higher
Memory: 32 MB RAM (minimum for Desktop Engine),64 MB RAM (minimum for all other editions),128 MB RAM or more recommended
Hard disk space:

270 MB (full installation),250 MB (typical),95 MB (minimum),Desktop Engine: 44 MB
Analysis Services: 50 MB minimum and 130 MB typical
English Query: 80 MB MySQL version 4.1 is not so powerful as SQL Server 2000 and uses less hardware resources.

To install MySQL version 4.1, you should have near 32 Mb RAM and near 60 Mb hard disk space. The general MySQL version 4.1 installation does not require additional CPU resources.

Software requirements: SQL Server 2000 comes in six editions: Enterprise, Standard, Personal, Developer, Desktop Engine, and SQL Server CE (a compatible version for Windows CE)

MySQL version 4.1 comes in two editions:

The Standard edition are recommended for most users and contains general MySQL features. The Max edition includes additional features such as the Berkeley DB storage engine, OpenSSL support, user-defined functions (UDFs), and BIG_TABLE support.MySQL version 4.1 requires the following software:

Platform
Operating System Version
Windows-based
Windows 95/98/NT/2000/XP/2003
Sun Solaris
Solaris 8 (SPARC)
FreeBSD
FreeBSD 4.x (x86)
Mac OS X
Mac OS X v10.2
HP-UX
HP-UX 10.20 (RISC 1.0),HP-UX 11.11 (PA-RISC 1.1 and 2.0),HP-UX 11.11 (PA-RISC 2.0, 64-bit only)
AIX-Based
AIX 5.1 (RS6000),AIX 4.3.2 (RS6000),AIX 4.3.3 (RS6000)
QNX
QNX 6.2.1 (x86)
SGI Irix
SGI Irix 6.5
Dec OSF
Dec OSF 5.1 (Alpha)

Performance comparison

It is very difficult to make the performance comparison between SQL Server 2000 and MySQL version 4.1. The performance of your databases depends rather from the experience of the database developers and database administrator than from the database’s provider. You can use both of these RDBMS to build stable and efficient system. However, it is possible to define the typical transactions, which used in inventory control systems, airline reservation systems and banking systems. After defining these typical transactions, it is possible to run them under the different database management systems working on the different hardware and software platforms.

TPC tests The Transaction Processing Performance Council (TPC.Org) is independent organization that specifies the typical transactions (transactions used in inventory control systems, airline reservation systems and banking systems) and some general rules these transactions should satisfy.The TPC produces benchmarks that measure transaction processing and database performance in terms of how many transactions a given system and database can perform per unit of time, e.g., transactions per second or transactions per minute.The TPC organization made the specification for many tests. There are TPC-C, TPC-H, TPC-R, TPC-W and some old tests, such as TPC-A, TPC-B and TPC-D. The most popular test is the TPC-C test (OLTP test).At the moment the article was wrote, SQL Server 2000 held the second position in the TPC-C by performance results. See Top Ten TPC-C by Performance Version 5 Results At the moment the article was wrote, SQL Server 2000 held the top TPC-C by price/performance results.See Top Ten TPC-C by Price/Performance Version 5 Results MySQL does not participate in TPC-C tests, they make their own benchmark tests. These tests are not independent, but if you interesting, see this link:The MySQL Benchmark Suite

Features comparison

Both SQL Server 2000 and MySQL version 4.1 support the ANSI SQL-92 entry level and do not support the ANSI SQL-92 intermediate level. In the Features comparison section of this article, I want to make the brief comparison of the Transact-SQL with MySQL dialect and show some SQL Server 2000 and MySQL version 4.1 limits.

T-SQL vs MySQL dialectThe dialect of SQL supported by Microsoft SQL Server 2000 is called Transact-SQL (T-SQL). The dialect of SQL supported by MySQL version 4.1 is called MySQL dialect. Transact-SQL dialect is more powerful language than MySQL dialect.

Conclusion

It is not true that SQL Server 2000 is better than MySQL version 4.1 or vice versa. Both products can be used to build stable and efficient system and the stability and effectiveness of your applications and databases depend rather from the experience of the database developers and database administrator than from the database’s provider. But SQL Server 2000 has some advantages in comparison with MySQL version 4.1 and vice versa.

The SQL Server 2000 advantages:

SQL Server 2000 holds the top TPC-C performance and price/performance results.
SQL Server 2000 is generally accepted as easier to install, use and manage.
Transact-SQL is more powerful language than MySQL dialect.

The MySQL version 4.1 advantages:

MySQL version 4.1 supports all known platforms, not only the Windows-based platforms.
MySQL version 4.1 requires less hardware resources.
You can use MySQL version 4.1 without any payment under the terms of the GNU General Public License. This is from MySQL version 4.1 documentation:MySQL Server was designed from the start to work with medium size databases (10-100 million rows, or about 100 MB per table) on small computer systems.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
No comments

MySQL and FirebirdSQL Top Open Source DB List

(originally from internetnews.com)

A report from Evans Data shows that FirebirdSQL and MySQL are the most popular open source databases currently in use.

The findings are part of Evans Data’s Database Development Survey of more than 400 developers. According to the survey, 52.9 percent said they are using MySQL and 51.6 percent said they were using FirebirdSQL.

PostgreSQL came in third at 14.8 percent, and Sleepycat’s Berkely DB (4.1 percent), GNU SQL (3.3 percent) and SAP DB (1.2 percent) rounded out the list.
The Firebird name became the subject of heated dispute in the open source community in 2003 when the Mozilla project re-named its next-generation browser Phoenix to Firebird. After bowing to pressure from the community and the FirebirdSQL project, Mozilla changed the name to Firefox last year.

According to Evans Data’s research, MySQL and FirebirdSQL are each fulfilling different niches.
“Firebird has a very strong position in what we define as edge databases that could be embedded databases — databases sitting at the periphery of the enterprise,” Evans Data analyst Joe McKendrick told internetnews.com. “MySQL had a stronger showing on the enterprise level.”

The distant third place showing by PostgreSQL in the Evans Data survey is likely related to its previous lack of proper Windows support, according to McKendrick. PostgreSQL version 8.0 of its database, which now includes native Windows support.
“In our survey, 90 percent of our developers work with or deployed to Windows platforms,” McKendrick explained. “Windows dominates this space, and a database that doesn’t run on Windows or doesn’t run effectively in Windows would have a fairly limited reach.”

Among the other findings of the Evans Data study is that data restoration capabilities have climbed over the past year. In 2003, 41 percent of respondents reported they could restore mission critical data within an hour. That number jumped to 62 percent in 2004.
Security also seems to a strong point for database administrators in 2004. Eighty-nine percent of respondents reported they had no database security breaches.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
No comments

« Previous Page