Thursday, July 30, 2009

Sample code for accessing mySQL from java

import java.sql.*;


public class DBConnect {

/**
* @param args
*/
public static void main(String[] args) {

Connection connection = null;

try {
String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/databaseName", "userName", "password");
}
catch (Exception e) {
e.printStackTrace();
}

Statement stmt;
String s;
String own;

try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM pet");
while (rs.next()) {
// Get the data from the row using the column name
s = rs.getString("name");
own = rs.getString("owner");
System.out.println(s + " owned by " + own);
}
}
catch (SQLException e) {
e.printStackTrace();
}
}

}

No comments: