Connecting to a mysql database with JDBC
By: admin - Tuesday, September 9th, 2008 at 11:02 amThis is a crucial step in designing a Java application, but many people over look a few important things though. There are different way to make the connection, but not all are created equal. Some are more efficient than others.
First, you need to import your classes. Here is where many people make their first mistake. They will say import java.sql.*. This will work but is very inefficient. This will import all classes that have the the prefix of java.sql, it will not include many redundant classes but it will make your program run slower. You should only import the classes you need. In this case you need three.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Second, I like to always set my variables when I initialize, that way I know what the value of it from the beginning. Many think this is a redundant step but it has saved me a great deal of headache in the past.
Connection connect = null;
Third, it is not required but when you load the driver for the connection use the newInstance() argument with it. It will let you create a dynamically loaded class for it.
Class.forName(“com.mysql.jdbc.Driver”).newInstance();
Now it is time for us to make our connection to the database. This is the simplest part of the process. You just specify the url, username, and password of the database. For security reasons, it is good to never use your root account in a program. If someone does get the user name and password, they will only have access to just one of the databases instead of all of them.
connect = DriverManager.getConnection(“url”, “user”, “password”);
iEntry 10th Anniversary
Java Faqs