DataBase transaction February 14, 2008
Posted by essamabdelaziz in DataBase.add a comment
transaction
A transaction is a set of one or more statements that are executed together as a unit, so either all of the statements are executed, or none of the statements is executed.
Using Transactions
There are times when you do not want one statement to take effect unless another one completes. For example, when the proprietor of The Coffee Break updates the amount of coffee sold each week, he will also want to update the total amount sold to date. However, he will not want to update one without updating the other; otherwise, the data will be inconsistent. The way to be sure that either both actions occur or neither action occurs is to use a transaction.
Disabling Auto-commit Mode
When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. (To be more precise, the default is for an SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)
The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode. This is demonstrated in the following line of code, where con is an active connection:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author javadb.com
*/
public class Main {
/**
* Updates tables using a transaction
*/
public void updateDatabaseWithTransaction() {
Connection connection = null;
Statement statement = null;
try {
Class.forName(“[nameOfDriver]“);
connection = DriverManager.getConnection(“[databaseURL]“,
“[userid]“,
“[password]“);
//Here we set auto commit to false so no changes will take
//effect immediately.
connection.setAutoCommit(false);
statement = connection.createStatement();
//Execute the queries
statement.executeUpdate(“UPDATE Table1 SET Value = 1 WHERE Name = ‘foo’”);
statement.executeUpdate(“UPDATE Table2 SET Value = 2 WHERE Name = ‘bar’”);
//No changes has been made in the database yet, so now we will commit
//the changes.
connection.commit();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
try {
//An error occured so we rollback the changes.
connection.rollback();
} catch (SQLException ex1) {
ex1.printStackTrace();
}
} finally {
try {
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().updateDatabaseWithTransaction();
}
}
Sun to buy MySQL for $1 billion February 13, 2008
Posted by essamabdelaziz in DataBase.add a comment
SAN FRANCISCO (AP) – Sun Microsystems Inc.’s deal to buy open-source software company MySQL AB for $1 billion deepens Sun’s bet that its road to prosperity lies in distributing free software that generates hefty maintenance fees and could sell more servers.
The acquisition, announced before the market opened Wednesday, gives Santa Clara-based Sun a foothold in the rapidly expanding market for database software for Web-based companies.
MySQL’s software is used by some of the world’s biggest Web sites to archive and retrieve information, and with people creating more Web content every day, demand for those services is quickly growing.
Sun, in a separate announcement, also pre-announced second quarter revenue that would narrowly exceed Wall Street estimates. Profit during the quarter would fall at the high end of analysts’ expectations, Sun said.
Sun is paying $800 million in cash and assuming $200 million in options to acquire MySQL. The Swedish company makes open-source database software used by companies such as online search leader Google Inc., popular Internet hangout Facebook Inc. and Finnish phone maker Nokia Corp.
Sun said the deal will help spread MySQL’s software to large corporations, which have been the biggest customers of Sun’s servers and software, and boost its distribution through Sun’s relationships with other server makers such as IBM Corp. and Dell Inc.
Sun believes it can sell more server computers and ring up higher maintenance fees by also offering software whose source code is publicly available for free.
MySQL competes with non-open-source offerings from Microsoft Corp. and Oracle Corp., which dominate database software for traditional businesses.
However, MySQL is the rapidly growing market leader in open-source database software, particularly among Web-based companies, where it commands about 80 percent of the global market, according to Sun Chief Executive Jonathan Schwartz.
Microsoft is less than 10 percent of that market, Schwartz said.
“We are really acquiring a database that customers and Web companies across the world have moved to at a breathtaking clip,” Schwartz said in an interview. “The titans of the Web all use MySQL — banks, automobile companies, pretty much all of the Fortune 500 runs MySQL in their shops.”
The acquisition, expected to close in the third or fourth quarter, takes pressure off Sun to spend some of the cash it has been accumulating. It also bolsters its software offerings with a well-known name in Internet data retrieval.
“This gives us access to every hot Web company on earth, and every company that will be hot 5 years from now,” Schwartz said. “For us, this is completely landscape-changing.”
Sun also said it expects second-quarter net income of between $230 million to $265 million, or 28 cents to 32 cents per share. Analysts surveyed by Thomson Financial were expecting profit of between 22 cents and 38 cents.
Sun predicts $3.6 billion in sales during the second quarter. Analysts were expecting, on average, $3.58 billion in sales.
The company was expected to release its results January 24.
Despite financial difficulties that have plagued Sun since the dot-com meltdown in 2001, the company has been accumulating a cash horde that reached $5.9 billion at the end of the 2007 fiscal year.
In recent quarters, as Sun has returned to profitability under new management and tightened cost controls, investors have pressured the company to spend some of its war chest in ways that boost its value.
Still, some shareholders remain skeptical about the company’s prospects.
Sun’s stock price has slid about 25 percent since the company’s 1-for-4 reverse stock split in November, an essentially cosmetic maneuver to remove the stigma of slumping shares.
In a reverse stock split, a company lowers the number of outstanding shares, boosting the value of each share, while keeping total market value unchanged.
As a result, Sun’s share price jumped from around $5 to more than $20, but has fallen sharply since then, closing Tuesday at $14.98 before the acquisition and results were announced.
Sun shares rose 55 cents, or more than 3 percent, to $15.53 Wednesday.
http://news.moneycentral.msn.com/ticker/article.aspx?Feed=AP&Date=20080116&ID=8050292&Symbol=IBM
Connection Pool September 21, 2007
Posted by essamabdelaziz in DataBase.add a comment
Connection Pool
|
connection pool |
| A set of connections maintained so that the connections can be reused when there is a future need for the conneciton. |
Connection pools are used to reduce the overhead of using a database. Establishing a connection to the database is a costly operation. A connection pool keeps a pool of open connections, each connection can be used for a time as needed, and then released back to the pool. A connection that has been released back to the pool can then be reused.
Connection pooling is especially important in server applications. The overhead of opening a new connection for each new client request is too costly. Instead, the database pool allows for a connection to be opened once and then reused for many requests.
DataSource
|
DataSource |
| A JDBC term (and interface name) used for a factory that is used to obtain connections. |
how I read a Microsoft Excel file from Java?… April 25, 2007
Posted by essamabdelaziz in DataBase.add a comment
Although I’m a java developer from along time but I didn’t try to deal with excel
But last weekend I was give session to a person who want to learn java and I was doing some hello world examples for him
I wanted to let him see A much dynamic example
Mainly my DB is Oracle and sometimes mysql but I was unable to make installation Fro oracle client on his machine because
His laptop configuration
So I had to use excel
So how I read a Microsoft Excel file from Java?…
be quiet it is easy
Assume you have an Excel file named c:\qa.xls (to download, see Resources).
Also suppose that the data is in a worksheet named qas and takes the following format:
Microsoft’s ODBC driver treats the first row in a spreadsheet as the column names and the worksheet name as the database name.
To access a spreadsheet with JDBC, you need to create a new ODBC data source. To create one in Windows 2000:
1. Go to “Control Panel”
2. Go to “Administrative Tools”
3. Go to “Data Sources”
4. Select “Add”
5. Choose “Microsoft Excel Driver” and “Finish,”
6. Then give the “Data Source Name” qa-list and select the workbook
7. When you are done you should see your new qa-list data source name:
Now the spreadsheet is available as an ODBC source.
Say that you would like to pull out all March 2000 entries. You will need to hit the data source with the following SQL query
select URL from [qas$] where Month=’March’ and Year=2000;
Note that the table name is the name of the worksheet with a $ appended to the end. You have to append the $ in order for the query to work. Why? Because. The brackets are there because $ is a reserved character in SQL. Life is never easy.
Now try ExcelReader on for size:
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
public class ExcelReader
{
public static void main( String [] args )
{
Connection c = null;
Statement stmnt = null;
try
{
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” );
c = DriverManager.getConnection( “jdbc:odbc:qa-list”, “”, “” );
stmnt = c.createStatement();
String query = “select URL from [qas$] where Month=’March’ and Year=2000;”;
ResultSet rs = stmnt.executeQuery( query );
System.out.println( “Found the following URLs for March 2000:” );
while( rs.next() )
{
System.out.println( rs.getString( “URL” ) );
}
}
catch( Exception e )
{
System.err.println( e );
}
finally
{
try
{
stmnt.close();
c.close();
}
catch( Exception e )
{
System.err.println( e );
}
}
}
}
In ExcelReader, the main() gets a connection to the spreadsheet, then pulls out all of the entries for March 2000.
http://www.javaworld.com/javaworld/javaqa/2001-06/04-qa-0629-excel.html
What is the difference between exception and error? April 18, 2007
Posted by essamabdelaziz in DataBase.add a comment
The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.
What is the difference between an argument and a parameter?- April 18, 2007
Posted by essamabdelaziz in DataBase.add a comment
[
While defining method, variables passed in the method are called parameters. While using those methods, v
alues passed to those variables are called arguments.
calculate difference between two dates April 17, 2007
Posted by essamabdelaziz in DataBase.add a comment
this Amethod to calculate difference between two dates
public static int actualDifference(java.util.Date date1, java.util.Date date2) {
GregorianCalendar gc1 = new GregorianCalendar();
GregorianCalendar gc2 = new GregorianCalendar();
gc1.setTime(date1);
gc2.setTime(date2);
long millies = gc2.getTimeInMillis() – gc1.getTimeInMillis();
return (int) (millies / 1000 / 24 / 60 / 60);
}
Compare 2 Dates in java April 13, 2007
Posted by essamabdelaziz in DataBase.add a comment
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ComPare2Dates {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
DateFormat df = new SimpleDateFormat(“MM/dd/yy”);
// Get Date 1
Date d1 = df.parse(“10/4/05″);
// Get Date 2
Date d2 = df.parse(“20/4/05″);// TODO Auto-generated method stub
System.out.println(d1.before(d2));//true
System.out.println(d2.after(d1));//true
System.out.println(d2.equals(d1));//false
}
}
Creeate DataBase trigger March 27, 2007
Posted by essamabdelaziz in DataBase.add a comment
it is an example to create trigger
this trigger increments the value of column (ID) with One
After Each new Row is Added
CREATE OR REPLACE TRIGGER “YourUserName”.TrigerName
BEFORE INSERT ON YourTableName
REFERENCING
NEW AS NEW
OLD AS OLD
FOR EACH ROW
Begin
SELECT NVL(MAX(ID)+1,1) INTO :new.ID FROM YourTableName;
End;
/
throws VS throw March 19, 2007
Posted by essamabdelaziz in DataBase.add a comment
Did you asked before about the difference between throws and throw ..?
Any way here’s the answer
The throws clause is part of a method declaration. It tells callers of that method what exceptions that method could throws.
A throw statement actually throws the exception.
void foo() throws BarException { // throws clause says this method [i]might[/i] throw BarException
if (some bar-like condition is met) {
throw new BarException(“Oh No! It’s Bar!”); // throw statement actually throws the exception
}
// we only get here if we didn’t throw the exception, so we go on executing this method
}