1. Create the project, download the MySQL driver package to add to classpath;
2. Main steps:
A. Load the drive Class.forName ("Com.mysql.jdbc.Driver");
B. Use this driver to connect to the database with parameters including database path, username, password Connection conn = drivermanager.getconnection ("jdbc:mysql://localhost/3306/ Gaoxiangyu "," root "," root ");
C. Get the Statement object used to execute the SQL statement: Statement STM = Conn.creatstatment ();
D.statement object can be executed excutupdate (SQL),//can only be implemented and deleted changes can not realize
ExecuteQuery (SQL);//Can be implemented, return resultset result set
Excute (SQL);//can execute any SQL, but the return value can only be a Boolean type
1 Packagecom.database;2 3 ImportJava.sql.*;4 Public classgetconnection {5 Public StaticString Diver = "Com.mysql.jdbc.Driver";6 Public StaticString DataBase = "Jdbc:mysql://localhost:3306/gaoxiangyu";7 Public StaticString name = "Root";8 Public StaticString password = "root";9 Ten One Public Staticjava.sql.Connection getconnection () { A Try{ -Java.sql.Connection conn =NULL; -Class.forName (Diver);//Load Driver theconn = Drivermanager.getconnection (Database,name,password);//connect to the database based on the database name, user, password - returnConn; -}Catch(Exception e) { - e.printstacktrace (); + } - return NULL; + A } at - Public Static voidMain (string[] args) { - //TODO auto-generated Method Stub - - } - in}
1 Packagecom.database;2 ImportJava.sql.*;3 Public classExcutesql {4 5 Public Static intUpdate (String sql,connection conn)throwssqlexception{6Statement st =conn.createstatement ();7 returnSt.executeupdate (SQL);//You can perform additions, deletions and changes8 }9 Ten Public StaticResultSet Search (String sql,connection conn)throwssqlexception{ OneStatement st =conn.createstatement (); A returnst.executequery (SQL); - } - the Public Static BooleanAny (String sql,connection conn)throwssqlexception{ -Statement st =conn.createstatement (); - returnst.execute (SQL); - + } - +}
1 Packagecom.database;2 3 Importjava.sql.Connection;4 ImportJava.sql.ResultSet;5 ImportJava.sql.ResultSetMetaData;6 Importjava.sql.SQLException;7 8 Public classDatabasetest {9 Public Static voidMain (String args[])throwssqlexception{Ten Try(Connection conn =getconnection.getconnection ()) { OneString SQL1 = "SELECT * from Gaoxiangyu.userinfo;"; AString sql2 = "INSERT into Gaoxiangyu.userinfo VALUES (7717, \ ' wudiyy\ ', \ ' root\ ')"; - Excutesql.update (SQL2, conn); - //System.out.println (Excutesql.any (SQL1, conn)); theResultSet result =Excutesql.search (SQL2, conn); - //retrieves the number, types and properties of this ResultSet object ' s columns. -ResultSetMetaData MetaData =Result.getmetadata (); - intCOULMN =Metadata.getcolumncount (); + while(Result.next ()) { - for(inti=1;i<=coulmn;i++){ +System.out.print (result.getstring (i) + ""); A } at System.out.println (); - } - } - } -}
Using Java JDBC to link the MySQL database process