In my previous post I have mentioned about the MySQL connector which facilitates the connection between MySQL and Java. Now it's time to connect the database in coding.
Before attempting the code make sure your MySQL is working. Also create a database in the MySQL named 'data' and create a table within it named 'testtable'. Please go through MySQL commands, (just the basic stuff) so that you can clearly understand the code.
Moreover testtable should have three columns which accept TEXT data type.
I have implemented the following code to check the connectivity of the MySQL.
Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Pradeepa Senanayake
*/
public class MySQLtest {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/data","root","root");
conn.createStatement().execute("insert into testtable values ('abc' , 'abc' , 'abc' );");
conn.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
~ Class.forName("com.mysql.jdbc.Driver"); ~
This will dynamically add the Class 'Driver' to the run-time by accessing the given path. This is the jdbc(Java DataBase Controller) driver needs to connect to MySQL.
~ Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/data","root","root");
This is the connection to the database from within the Java program.
Here, you should note that "data" is the database name. "root" is the username and password for MySQL.
If your database name, username and the password are different, you should change the command accordingly.
~ conn.createStatement().execute("insert into testtable values ('abc' , 'abc' , 'abc' );"); ~
This is how we send a command to MySQL.
insert into testtable values ('abc' , 'abc' , 'abc' ); >>
This is a standard MySQL command to add 'abc' text value to the first three columns in the 'testtable' table.
So basically the command is,
conn.createStatement().execute( ***Database Command As A String*** );
That's it, if you did all of the above correct your program should work. And after you executed your program make sure your database is updated.
Thank you.