Category Archives: Java

JDBC Connectivity in Java(MySql)

  • Download JDBC driver from here
  • Add the downloaded jar file at appropriate place (if using Eclipse/Netbeans add the jar file to the project)
  • Change the connection string and server credentials accordingly

import java.sql.*;
public class JavatoMySql {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost/demo"; /demo is the name of the database
String user = "root"; //my sql username
String password = "root"; // my sql password

try {
  Class.forName("com.mysql.jdbc.Driver"); //loads the driver
  Connection con = DriverManager.getConnection(url, user, password);
  PreparedStatement ps=(PreparedStatement) con.prepareStatement("select * from table1");
  ResultSet rs=ps.executeQuery();
   System.out.println(rs.getString(1)) ; //print the first column of the table1
 }catch (Exception e) {
} //end of main
} //end of class