MySQL Programming in Java

Connecting to Database:
String url = "jdbc:mysql://hostname:portNumber/databaseName";
String username = "dbuser";
String password = "secret";
Connection conn = DriverManager.getConnection(url, 
   username, password);

Executing SQL Statements:

To execute a SQL statement, you first create a Statement object.
Statement stat = conn.createStatement();
Next, place the statement that you want to execute into a string, for example,
String command = "UPDATE Books"
   + " SET Price = Price - 5.00"
   + " WHERE Title NOT LIKE '%Introduction%'";
Then call the executeUpdate method of the Statement class:
stat.executeUpdate(command);
The executeUpdate method can execute actions such as INSERT, UPDATE, and DELETE as well as data definition statements such as CREATE TABLE and DROP TABLE. However, you need to use the executeQuery method to execute SELECT queries. There is also a catch-all execute statement to execute arbitrary SQL statements. It's commonly used only for queries that a user supplies interactively.

When you execute a query, you are interested in the result. The executeQuery object returns an object of type ResultSet that you use to walk through the result one row at a time.
ResultSet rs = stat.executeQuery("SELECT * FROM Books")

The basic loop for analyzing a result set looks like this:
while (rs.next())

{
   look at a row of the result set
}

If your connections are short-lived, you don't have to worry about closing statements and result sets. Just make absolutely sure that a connection object cannot possibly remain open by placing the close statement in a finally block:
try
{
   Connection conn = . . .;
   try
   {
      Statement stat = conn.createStatement();
      ResultSet result = stat.executeQuery(queryString);
      process query result
   }
   finally
   {
      conn.close();
   }
}
catch (SQLException ex)
{
   handle exception
}


To lunch a Java program from the command line:
##under Linux
java -classpath .:/path/to/driverJar ProgramName 
##under Windows
java -classpath .;c:\path\to\driverJar ProgramName 

MySQL Driver_url : jdbc:mysql://hostname:portNumber/databaseName
for example: jdbc:mysql://localhost/books

No comments: