Connect to MySQL database

How to connect from Java to MySQL database? Java runs on the local computer, and the database is located on the remote server.

+2
java database mysql connection
source share
2 answers

This example connects to a MySQL database using the MM JDBC driver for MySQL:

Connection connection = null; try { // Load the JDBC driver String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver Class.forName(driverName); // Create a connection to the database String serverName = "localhost"; String mydatabase = "mydatabase"; String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url String username = "username"; String password = "password"; connection = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { // Could not find the database driver } catch (SQLException e) { // Could not connect to the database } 

To run this example, you need to have an account in the MySQL database. To create an account, you can connect to the MySQL database on your platform with administrator rights and run the following command:

 mysql> GRANT SELECT, INSERT, UPDATE, DELETE PRIVILEGES ON *.* TO username@localhost IDENTIFIED BY 'password' WITH GRANT OPTION; 
+10
source share

JDBC, of ​​course. Get the mysql connector-j jar , put it in your classpath and read the docs .

+4
source share

All Articles