Connect To A MySQL Database


/ Published in: Java

This code snippet shows how to connect to a MySQL database using Connector/J.


Copy this code and paste it in your HTML
  1. import java.sql.*;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4.  
  5. class Example{
  6. public static void main(String args[]){
  7. String driver = "com.mysql.jdbc.Driver";
  8. String connection = "jdbc:mysql://localhost:3306/database_name";
  9. String user = "";
  10. String password = "";
  11. try{
  12. Class.forName(driver);
  13. Connection con = DriverManager.getConnection(connection, user, password);
  14. if (!con.isClosed()){
  15. Statement stmt = con.createStatement();
  16.  
  17. ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
  18.  
  19. while(rs.next()){
  20. System.out.println(rs.getString("First_Name"));
  21. }
  22. }
  23. }catch(Exception e){
  24. System.out.println(e.getMessage());
  25. }
  26. }
  27. }

URL: http://www.snippetcentral.net/java/connect-to-a-mysql-database.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.