Basic steps to implement:
1. Load the driver:
Class.forName ("Com.mysql.jdbc.Driver");
2, access to data can be connected:
Private static final String URL = "Jdbc:mysql://localhost:3306/shopping?useunicode=true&characterencoding=utf-8 &usessl=false "; Database address private static final String usename = "root"; Private static final String password = "root"; Database password Connection Connection = drivermanager.getconnection (Url,user,password);
Where jdbc in the URL represents the connection mode, MySQL indicates that the database software represents the database address for Mysql,localhost, 3306 represents the database port, and shopping represents the database name.
3, through the database connection operation database, to achieve additions and deletions to search
Statement Statement = Connection.createstatement ();
ResultSet ResultSet = Statement.executequery ("SELECT * from goods;"); Used to perform database queries
ResultSet ResultSet = Statement.executeupdate ("");//used to perform database updates
Another way to execute SQL statements:
PreparedStatement pstatement = Connection.preparestatement (""); Compile SQL code pstatement.execute (); Execute SQL code
The following is a complete test code:
Package Util;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.resultset;import Java.sql.sqlexception;import Java.sql.statement;public class DBHelper {private static String Driver = " Com.mysql.jdbc.Driver "; Database driver//Connection database URL address private static final String URL = "jdbc:mysql://localhost:3306/shopping?useunicode=true& Characterencoding=utf-8&usessl=false ";p rivate static final String usename =" root ";p rivate static final string Password = "root"; The database password private static Connection Connection =null;//Static code block is responsible for loading the code in the driver static{//static block will take precedence to execute try {class.forname (driver);} catch (ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Singleton mode returns the database Connection object public static Connection getconnection () {if (connection==null) {try {Connection = Drivermanager.getconnection (Url,usename,password);} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return connection;} return connection;} public static void Main (string[] args) {ResultSet resuLtset = null;try{connection Connection = dbhelper.getconnection (); Statement Statement = Connection.createstatement (); ResultSet = Statement.executequery ("SELECT * from goods;"); while (Resultset.next ()) {System.out.println (resultset.getstring ("name"));}} catch (Exception e) {e.printstacktrace ();}}}
Bridging the bridge between Java and MySQL--jdbc