In this article, I show you how to connect to MySQL 5.0 from Java. We will see how to install MySQL 5.0 and use JDBC driver for MySQL 5.0.
Once you installed and created required objects in MySQL, use the following steps to download .NET provider for MySQL.
The following program loads JDBC driver and connects to mysql database in MySQL 5.0 running on the localhost (current system).
import java.sql.Connection; import java.sql.DriverManager; public class ConnectToMySql { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); /* mysql is the name of the database. Substitute mysql with name of database, in case you want to connect to a different database */ Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mysql?user=root&password=srikanth"); System.out.println("Connected To MySql 5.0"); con.close(); } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ListAddresses { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mysql?user=root&password=srikanth"); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from addresses"); while ( rs.next()) { System.out.println( rs.getString("name") + ":" + rs.getString("email")); } rs.close(); st.close(); con.close(); } }The next program shows how to call a stored procedure of MySQL. Stored procedure is a program that is stored in the database. It can be called from front-ends like Java program. First we have to create a stored procedure by connecting to MySQL. Create a procedure with the following code:
DELIMITER $$ CREATE PROCEDURE ChangeEmail(p_name varchar(30), p_email varchar(50)) BEGIN UPDATE addresses SET email= p_email where name = p_name; END $$ DELIMITER ;First and last lines in the above code are used to change the delimiter in MySQL Command Line. Procedure ChangeEmail is used to change email address of the given name. Now, let us see how to call this procedure from Java.
import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; public class CallProcedure { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mysql?user=root&password=srikanth"); CallableStatement cs = con.prepareCall("{ call ChangeEmail(?,?)}"); cs.setString(1,"P.Srikanth"); cs.setString(2,"srikanthpragada@yahoo.com"); cs.execute(); cs.close(); con.close(); } }