The database was designed last week using the Java language and MySQL database, which involves knowledge of the Java connection database.
- First we need to add a jar file that is equivalent to a driver file for the connection, and here I add this file:
mysql-connector-java-5.1.13-bin.jar
- Then we can be connected to the database, in Java to do some database operations: increase, delete, change, check;
- Then create a user class in Java and create a user table in MySQL:
PackageEntity Public class user { Private intIdPrivateString user;PrivateString pwd;PrivateString Mark; Public int getId() {returnId } Public void setId(intID) { This. id = ID; } PublicStringGetUser() {returnUser } Public void SetUser(String user) { This. user = user; } PublicStringgetpwd() {returnPwd } Public void setpwd(String pwd) { This. pwd = pwd; } PublicStringGetmark() {returnMark } Public void Setmark(String Mark) { This. Mark = Mark; }}
- Then we can do some operations in the database in Java:
Add: Delete and update operations and increase the same, just change the database statements.
Public int AddUser(User u) {List<user> List =NewArraylist<user> (); Connection ct =NULL; PreparedStatement PS =NULL; ResultSet rs =NULL;intresult =0;Try{Statement STA =NULL; Class.forName ("Com.mysql.jdbc.Driver"); ct = drivermanager.getconnection ("JDBC:MYSQL://127.0.0.1:3306/WHJ","Root","");//Connect to databaseString sql =INSERT INTO User (User,pwd,mark) VALUES (' "+u.getuser () +"', '"+u.getpwd () +"', '"+u.getmark () +"')";//Insert New userSTA = Ct.createstatement (); result = Sta.executeupdate (SQL); }Catch(Exception e) {E.printstacktrace (); }returnResult }
Inquire:
Public int GetUser(User u) {List<user> List =NewArraylist<user> (); Connection ct =NULL; PreparedStatement PS =NULL; ResultSet rs =NULL;Try{Statement STA =NULL; Class.forName ("Com.mysql.jdbc.Driver");//Load driverct = drivermanager.getconnection ("JDBC:MYSQL://127.0.0.1:3306/WHJ","Root","");//Connect to databaseString sql ="SELECT * from User";//Query All usersPS = (preparedstatement) ct.preparestatement (SQL); rs = Ps.executequery (); while(Rs.next ()) {User Use =NewUser (); Use.setid (Rs.getint ("id")); Use.setuser (Rs.getstring ("User")); Use.setpwd (Rs.getstring ("PWD")); Use.setmark (Rs.getstring ("Mark")); List.add (use); } for(inti =0; I < list.size (); i++) {User Use = List.get (i);if(Use.getuser (). Equals (U.getuser ())//To verify the judgment&& use.getpwd (). Equals (U.getpwd ())) {return 0; }if(i = = List.size ()-1) {return-1; }} ct.close (); }Catch(Exception e) {E.printstacktrace (); }return-1; }
Then this is the basic operation of the connected database in Java.
Connect MySQL database in Java