Connect Java program to MySQL Cluster
This article briefly introduces how to create and configure a MySQL cluster in a Windows environment. Here, we use a Demo that implements the registration function to connect to the MySQL cluster through jdbc.
To remotely connect an external program to a mysql cluster, you also need to set the mysql node to be remotely connected.
The specific operations are as follows:
mysql> grant all privileges on MySQL_Cluster_Test.* to root@'%' identified by ''; mysql> flush privileges;
Grant all tables in the database MySQL_Cluster_Test to all machines. The login name is root and the password is blank. If you only specify a machine to connect to this data node, replace "%" with the corresponding IP address.
UserDAO code:
Public class UserDAO {/*** Add User * @ param name username * @ param age user age * @ return */public boolean AddUser (String name, int age) {boolean result = false; // default value of the returned value is false Connection conn = null; // create a database Connection object Connection PreparedStatement pstmt = null; // create a preprocessing object PreparedStatement try {// register the driver Class. forName (com. mysql. jdbc. driver); // establish the connection conn = DriverManager. getConnection (jdbc: mysql: // 192.168.25.48: 3306/MySQL_Cluster_Tes T, root,) ;}catch (Exception e) {e. printStackTrace () ;}try {String SQL = insert into T_User (Name, Age) values (?,?); Pstmt = conn. prepareStatement (SQL); pstmt. setString (1, name); pstmt. setInt (2, age); int countw.pstmt.exe cuteUpdate (); // update the database and return the affected rows if (count> 0) {result = true;} catch (Exception e) {e. printStackTrace ();} return result;}/*** query all users * @ return List
*/Public List
QueryAllUsers () {List
UserList = new ArrayList
(); Connection conn = null; Statement stmt = null; try {// register the driver Class. forName (com. mysql. jdbc. driver); // establish the connection conn = DriverManager. getConnection (jdbc: mysql: // 192.168.25.48: 3306/MySQL_Cluster_Test, root,);} catch (Exception e) {e. printStackTrace ();} try {String SQL = select * from T_User; stmt = conn. createStatement (); ResultSet rs initialize stmt.exe cuteQuery (SQL); while (rs. next () {User tmpUser = new User (); tmpUser. setName (rs. getString (Name); tmpUser. setAge (rs. getInt (Age); userList. add (tmpUser) ;}} catch (SQLException e) {e. printStackTrace ();} return userList ;}}
If the preceding MySQL cluster is configured, external programs released on multiple servers can share and operate the data in the entire cluster. However, the MySQL cluster cannot achieve load balancing and read/write splitting at this time, but it only plays a role in data backup. We will continue to study how to achieve load balancing and read/write splitting for MySQL clusters.