Reputation: 973
I want to create a java program which can connect to an online mySQL database. I have done some research and figured out that I should use an online mySQL database. In java, I understand there is a JDBC library for connecting to databases. How can I connect to the database online with reading and writing to it? I am looking into using the Google Cloud SQL. It says to connect to it like any other mySQL Database.
Google Cloud SQL:Website
Basically, my main question is: How can I connect to an online mySQL database with reading and writing to it from a java application?
Edit: Also is there any example for reading and writing to the database, not just how to connect?
Upvotes: 2
Views: 3562
Reputation: 130
You will need a connector, you can find at http://dev.mysql.com/downloads/connector/j/ Then you install, and next you should put in your build path, if you are using the eclipse, go right click on your project folder, properties, java build path libraries adn add external jar (the jar must be C:\Program Files \MySQL\MySQL Connector as mysql-connector-java-5.1.35-bin.jar ), next go order and export, select the jar imported and save.
After that you have installed the api to connect to the database for mysql
String mysql_jdb_driver = "com.mysql.jdbc.Driver"; // the connector for the database
String mysql_db_url = "jdbc:mysql://localhost/notas"; // url to connect, in this case is local but you can connect to an ip
String mysql_db_user = "root"; // DB user name MYSQL
String mysql_pass = ""; //DB password
try{ //try to connect to the DB
Class.forName(mysql_jdb_driver).newInstance();
conn = DriverManager.getConnection(mysql_db_url,mysql_db_user, mysql_pass );
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ...");//put your select here
stmt.executeUpdate("INSERT ...");//put insert, delete here
}
catch(Exception ex){
ex.printStackTrace();
}
finally // always close the connecttion
{
conn.close();
}
Upvotes: 3
Reputation: 4451
as Roman suggested, all you need is in the link. If your application is not on the App Engine, just use include the mysql driver on the project and create the connection. Take a look at this: MySQL docs
Upvotes: 2