Friday, February 29, 2008

JDBC Connection to MySQL

Now that Sun has acquired MySQL, the combination of java and MySQL is going to be the next big thing in the market. Today I will present a small tutorial on how you can connect to MySQL using JDBC. This procedure is tested under windows platform with jdk 1.6.
Pre-requisites:-
  1. JDK- download
  2. MySQL- download
  3. JDBC connector - link given below.
  • You need to download the driver Connector/J zip from MySQL website. Here is the download link.
  • Extract the zip file.
  • After extracting you will find a JAR file inside the unzipped directory.
  • Copy the JAR file to "jre path"\lib\ext
  • Now take the help of the following example to proceed.
import java.sql.*;
public class jdbc_mysql
{
public static void main(String args[])
{
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn=null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/dbname?"+
"user=user_name&password=your_password");
stmt=conn.prepareStatement("select * from student where name=?");
stmt.setString(1,args[0]);
rs=stmt.executeQuery();
if(rs.next()==false)
System.out.println("Record not found!!!");
else
{
String s=rs.getString(2);
System.out.println(s);
}
}
catch(Exception e)
{
System.err.println("Exception: " + e.getMessage());
}
}
}
Sorry for the clumsy indentation. It got deformed when I pasted my code in the blogger editor. If you have any further queries please feel free to leave a comment. I will address your query as soon as possible.

0 comments:

Disclaimer

Experiment with the things mentioned in this blog at your own risk. The author shall not be held responsible for any damages caused to your system by the things mentioned in the blog.

Notice

All logos, trademarks, images used are property of their respective organizations. If any organization has objection to any post regarding use of their property I will happily remove it.