2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Connect Java to a MySQL database

Can anybody explain how to connect MySQL with java?
userimage

Let"s first create a table in the mysql database, but before creating table, we need to create database first.


try{ 
Class.forName("com.mysql.jdbc.Driver"); 
 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","root"); 
 
//here mysql is database name, root is username and password 
 
Statement stmt=con.createStatement(); 
ResultSet rs=stmt.executeQuery("select * from Emp");  //here Emp is your table name
while(rs.next()) 
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3)); 
 con.close(); 
 
}catch(Exception e){ System.out.println(e);} 
 
}
Answer is