package packagename;import java.sql.connection;import java.sql.drivermanager;import java.sql.preparedstatement;import java.sql.resultset;import java.sql.sqlexception;import Java.sql.statement; public class classname { public static String url = "Jdbc:mysql://localhost:3306/test";//characterencoding=gbk public static String username = "Root"; public static string password = "root"; public static connection con; public static statement stmt; public static ResultSet rs; public static PreparedStatement Pstmt; public static void main (String[] args) throws sqlexception&nbSp { connect (); // Select (); //insert (); //update (); //delete (); close (); } public static void Connect () { // positioning drive try { Class.forName ("Com.mysql.jdbc.Driver");  SYSTEM.OUT.PRINTLN ("Load driver succeeded!"); } catch (classnotfoundexception e) {             SYSTEM.OUT.PRINTLN ("Load driver failed!"); &nbsP; e.printstacktrace (); } // establishing a connection try { con = drivermanager.getconnection (Url, username, password); stmt = con.createstatement ();          SYSTEM.OUT.PRINTLN ("Database connection succeeded!"); } catch (sqlexception e) {           SYSTEM.OUT.PRINTLN ("Database connection failed!"); e.printstacktrace (); } } public static void select () { try { string sql= "select * from test where name=? "; pstmt=con.preparestatement (SQL); pstmt.setstring (1, "root"); //string sql= "Select * from test where name= ' root ' "; //rs = Stmt.executequery (SQL); rs=pstmt.executequery (); while (Rs.next ()) { &nBsp; system.out.println ("Your first field content is:" +rs.getstring ("name")); system.out.println ("Your second field content is:" +rs.getint (1)); } rs.close (); }catch (exception e) {   SYSTEM.OUT.PRINTLN ("Data query failed!"); e.printstacktrace (); } } public static void insert () { try { string sql= "insert into test (id,name) valuEs (' 2 ', ' admin ') "; stmt.executeupdate (SQL);           SYSTEM.OUT.PRINTLN ("Data insertion succeeded!"); }catch (exception e) {         SYSTEM.OUT.PRINTLN ("Data insertion failed!"); e.printstacktrace (); } } public static void update () { try { string sql= "update test Set name= ' Rootroot ' where id=1 "; stmt.executeupdate (SQL); system.out.println ("Data Update successful!"); }catch (exception e) {         SYSTEM.OUT.PRINTLN ("Data update failed!"); e.printstacktrace (); } } public static void delete () { try { string sql= "delete from test where id=?"; pstmt = con.preparestatement (SQL); pstmt.setint (; ) pstmt.executeupdate (); & nbsp; system.out.println ("Data deleted successfully!"); }catch (exception e) {         SYSTEM.OUT.PRINTLN ("Data deletion failed!"); e.printstacktrace (); } } public static void close () { try{ if (rs!=null) rs.close (); if (stmt!=null) Stmt.close (); if (Con!=null) con.close (); }catch (Exception e) { e.printstacktrace (); } } }
Java Connection MySQL Database sample