10 September 2013

MySql connection string to connect with MySql database in Java


Hi Friends,

Lets see how to use the mysql connector jar file to create the connection with MySql database in Java.
As MySql is freeware sometime we think about to use the MySql with our Java application but we get failed to create the connection with MySql db.

You need to add the reference of mysql connector jar file to your project to create the connection with MySql database. You can download this connector jar file from here.

You can also download the net-beans MySql connection sample project from here. Its a zip file just extract it and Net Beans project is ready.

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mysqlconnection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * * @author DeepakSharma */ public class MySqlConnection { /** * @param args the command line arguments */ public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); /** * TODO you need to provide the db user to access db * and the password of that user */ Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/YOUR_DB?user=db_user_name&password=db_user_password"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from tableA"); while(rs.next()) { // TODO database login goes here System.out.println(rs.getInt(1) +"/"+ rs.getString(2)); } System.out.println("done"); } catch (Exception ex) { ex.printStackTrace(); } } }

Happy Coding.. :)

No comments:

Post a Comment