Although the majority of my programming efforts evolve around C# & ASP.NET using C#, I find myself doing more stuff with Java. As with every new language that I work with, there are specific things which are common across all languages, such as reading flat files and parsing delimited strings, reading and writing XML files and of course, connecting to a database that I tend to focus on.
The other day, I found myself needing to connect to a MySQL Database, so I downloaded the JDBC Driver (jar file) that would enable me to connect a small java app and read some data. I downloaded it from the java web site, you can do a search for “download jdbc drivers” and you should find the url.
Next, I created a new project in Eclipse and added a .java file. Be sure to add the .jar file for the jdbc driver to the build path of your Eclipse project or you will get an error when you try use the DriverManager and try to connect to the database.
Here is the code that I used:
Add the following import statement:
import java.sql.*;
Add the following module level variables.
static Connection conn;
static Statement stmt;
static ResultSet rset;
try {
Class.forName(”com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/
yourdatabase”, “loginid”, “loginpw”);
stmt=conn.createStatement();
rset = stmt.executeQuery(”SELECT *
FROM ssfsigma.csaccount”);
while(rset.next()) {
System.out.println(rset[1].getString() );
}
}
catch( Exception ex ) {
System.out.println(ex.getMessage());
return;
}
Using the DriverManager object, I call the getConnection() method. The Statement is like the SqlCommand object, so I call CreateStatement() on the Connection object. Once I have my Statement, I create a ResultSet by using the executeQuery() method. After this, I can read each record in the ResultSet using the .next() method.
Notice that the connection string contains localhost:3306. This is the port that is defaulted in the install of MySQL.