Connect to MAMP MySql with Java JDBC
Probably the easiest way to develop PHP/MYSQL Applications on the Mac is to install MAMP. However, if you then want to add Java capabilities to this there is very little documentation that explains what you need to do. After much digging around its actually rather easy assuming you are using the JDBC connector – this is how.
Allow MYSQL Networking
JDBC connects to mysql via an IP Address rather than a socket so you need to allow for networking in the my.cnf file. If you are using MAMP PRO you can just boot MAMP Admin and go to File > Edit Template > my.cnf before finding the line that says skip_networking and just uncomment it. Normal MAMP requires a bit more work and this link should help. Restart your Apache/MySql services.
Set Up a Basic Java MySQL Connection
The following is an example java connection function:
private static Connection connect() {
Connection conn = null;
try {
String userName = "EXAMPLE-USER";
String password = "EXAMPLE-PASSWORD";
String url = "jdbc:mysql://localhost:3306/EXAMPLE_DATABASE";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Database connection established");
} catch (Exception e) {
System.err.println("Cannot connect to database server");
e.printStackTrace();
}
return conn;
}
Add the JDBC Library
If you right click on Libraries folder in the Project Window of Netbeans you should see an option to Add Library. Click this and scroll down until you find MySql JDBC. Select it and Bob is your uncle. Everything should run just Dandy now.
This was really helpful. We did need to do this >>
http://tglei.blogspot.com/2012/11/javalangclassnotfoundexception.html
and in the MAMP PRO MySQL Tab, uncheck “Allow local access only”.
After that it worked perfectly.
Hi Sunjay,
I’m surprised you needed to uncheck ‘Allow local access only’ as this option limits you to localhost. Maybe you are not running as localhost on your machine but that would be odd as I thought it was default. Be aware this means your mysql server is open to attack from other machines on the network. Restricting access to local machine only is a standard way of securing mysql servers used in conjunction with web servers. Only websites hosted on the same machine can connect with the mysql server.
Otherwise, glad you found the post helpful. Best Regards
Thanks. Just a note: On my version on MAMP Pro the name of the variable in the my.cnf file was “MAMP_skip-networking_MAMP”
Pingback: Using Java with MySQL through MAMP | Paris Fox
Pingback: Using Java with MySQL through MAMP | JaScript