Java programs can be linked to the database through the JDBC, JDBC can easily access the database, do not have a specific database to write a special program.
Need to configure Mysql-connector-java-5.0.8-bin.jar first
The development process for connecting to a database using JDBC is as follows:
- Register Database Driver Class.forName ("Com.mysql.jdbc.Driver");
- The connection URL for the url,mysql that builds the database connection is "Jdbc:mysql://localhost:3306/test"
- Gets the connection object, which is a JDBC-encapsulated database connection object that can be used to perform operations on the data only after the object is created. Drivermanager.getconnection (URL, username, password);
The following are the five interfaces for the JDBC Core API:
Example: MySQL data table format:
Add the core code of the operation:
Try{class.forname ("Com.mysql.jdbc.Driver"); String URL= "Jdbc:mysql://localhost:3306/student"; Connection Con=drivermanager.getconnection (URL, "root", "" "); String SQL= "INSERT into Tb_books (name, Price, Bookcount, author) values (?,?,?,?)"; PreparedStatement PS=con.preparestatement (SQL); Ps.setstring (1, Book.getname ()); Ps.setdouble (2, Book.getprice ()); Ps.setint (3, Book.getbookcount ()); Ps.setstring (4, Book.getauthor ()); introw =ps.executeupdate (); if(row>0) {Out.print ("Successfully added" +row+ "row Data"); } ps.close (); Con.close ();}Catch(Exception e) {out.print ("Add failed!"); E.printstacktrace ();}
The core code of the query operation:
Try{class.forname ("Com.mysql.jdbc.Driver"); String URL= "Jdbc:mysql://localhost:3306/student"; Connection Con=drivermanager.getconnection (URL, "root", "" "); Statement Statement=con.createstatement (); String SQL= "SELECT * FROM Tb_books"; ResultSet RS=statement.executequery (SQL); ArrayList<Book> list=NewArraylist<book>(); while(Rs.next ()) { Book Book=NewBook (); Book.setname (Rs.getstring ("Name")); Book.setprice (Rs.getdouble ("Price")); Book.setbookcount (Rs.getint ("Bookcount")); Book.setauthor (Rs.getstring ("Author")); List.add (book); } request.setattribute ("List", list); Rs.close (); Con.close (); } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); }
To modify the core code of the data:
Try { class.forname ("Com.mysql.jdbc.Driver"); String URL= "jdbc:mysql://localhost:3306/student"; Connection con=drivermanager.getconnection (url, "root", ""); String SQL= "Update tb_books set bookcount=?" where Name=? " ; PreparedStatement ps=con.preparestatement (sql); Ps.setint (1, bookcount); Ps.setstring (2, name); Ps.executeupdate (); Ps.close (); Con.close (); } Catch (Exception e) { e.printstacktrace (); }
Similar to other operations on data.
MySQL's JDBC