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:-
Pre-requisites:-
- 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:
Post a Comment