Khalsa Labs

Connect Java and MySQL

How to connect Java and MySQL

This Tutorial Lets You easily Connect java and  MySQL in small code and efforts. As the Java is widely known and used programming language and MySQL is widely used database in field of Information Technology. Lets Combine them both.

 

  • Install MySQL drivers for Java , before start,  install from here
  • Create  a Class Named ‘ mycon ‘ in Java and Write code as follow:


import java.sql.*;
public class mycon {
String url = "jdbc:mysql://localhost:3306/";
String driver = "com.mysql.jdbc.Driver";
String dbname = "testDB";    // testDB is my database name , write your database name here
String pass = "";
String usr = "root";
Connection con = null;
PreparedStatement st;
ResultSet rs;
public void dbinitial()
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception ex)
{
System.out.println("sorry error in connection =" +  e);
}
}
try
{
con = DriverManager.getConnection(url+dbname,usr,pass);
ResultSet rs =  obj.select("select * from students" );                          // you could write your own select query.
while(rs.next())
{
string s_ name =  rs.getString("name");
System.out.print(s_name);
}
}
catch(Exception e)
{
System.out.println("statement error =" + e);
}
}

In Above Class only for Select from tables in database is discussed.
I’ll write update, delete methods and explain the Code in another post… Enjoy Java 🙂

The following two tabs change content below.
Python Developer and DIY lover.

want to comment ??

Your email address will not be published. Required fields are marked *