The previous section describes how to set up a MySQL cluster in a Windows environment, where a small demo that implements the registration function is connected to the MySQL cluster in a JDBC way.
An external program that wants to connect remotely to a MySQL cluster is one of the things that you need to do to set up a SQL node for MySQL to be remotely connected.
Detailed actions are:
mysql>allon MySQL_Cluster_Test.*to [email protected]‘%‘by‘‘; mysql> flush privileges;
Indicates that all tables in this database will be mysql_cluster_test to all machines, and the login name is root. Password is empty. Suppose you only specify that a machine can connect to this data node. The "%" can be replaced by the corresponding IP.
Userdao Code:
Public class Userdao{ /** * Join user * @param name username * @param Age user * @return * * * Public Boolean AddUser(String name,intAge) {Booleanresult=false;//return value default feel falseConnection conn=NULL;//CREATE database Connection object ConnectionPreparedStatement pstmt=NULL;//Create preprocessing object PreparedStatement Try{//Brochure DriveClass.forName ("Com.mysql.jdbc.Driver");//Establish connectionConn=drivermanager.getconnection ("Jdbc:mysql://192.168.25.48:3306/mysql_cluster_test","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);intCount=pstmt.executeupdate ();//Update the database and return the number of affected rows if(count>0) {result=true; } }Catch(Exception e) {E.printstacktrace (); }returnResult }/** * Query All users * @return list<user> */ PublicList<user>queryallusers() {list<user> userlist=NewArraylist<user> (); Connection conn=NULL; Statement stmt=NULL;Try{//Brochure DriveClass.forName ("Com.mysql.jdbc.Driver");//Establish connectionConn=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 =stmt.executequery (SQL); while(Rs.next ()) {User tmpuser=NewUser (); Tmpuser.setname (Rs.getstring ("Name")); Tmpuser.setage (Rs.getint ("Age")); Userlist.add (Tmpuser); } }Catch(SQLException e) {E.printstacktrace (); }returnuserlist; }}
Assuming that the previous MySQL cluster is configured, it is possible to implement external programs advertised on multiple servers to share and manipulate the data in the entire cluster.
However, the MySQL cluster is not able to achieve the effect of load balancing and read-write separation, just play the role of data backup.
Later, we will continue to study how to implement load balancing and read/write separation of MySQL cluster.
(The above is just the main code, assuming the entire project, can click "" Download source code)
"MySQL cluster"--java program connects MySQL Cluster