Java database connection (Java DB connectivity abbreviation JDBC) download JDBC Driver: https://dev.mysql.com/downloads/connector/j/ The Windows system downloads the. zip file package, Linux platform download tar.gz package to find the Gcfjmysql-connector-java-[version]-bin.jar package, JDBC through this file can be properly connected to the database. Open eclipse--Right-click the project--build path--add External JARs Browse the jar package you just downloaded. After Apply and Close, you can find the jar package you just added in the project directory
Next we create a new dbhelper simple data access class with the following code:
PackageCom.llt.demo;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement; Public classDBHelper { Public Static FinalString url = "Jdbc:mysql://127.0.0.1/test"; //Jdbc:mysql://host:port/database name Public Static FinalString name = "Com.mysql.jdbc.Driver"; Public Static FinalString user = "root"; //Database Login User Public Static FinalString password = "123456"; PublicConnection Connection =NULL; PublicPreparedStatement PST =NULL; //Database Login Password Publicdbhelper (String sql) {Try{class.forname (name);//Specify connection TypeConnection = drivermanager.getconnection (URL, user, password);//Create a connectionPST = connection.preparestatement (SQL);//Execute SQL statement } Catch(Exception e) {e.printstacktrace (); } } Public voidClose () {Try { This. Connection.close (); This. Pst.close (); } Catch(Exception e) {}}}
View Code
Then create a simple class that tests the MySQL database to connect
PackageCom.llt.demo;ImportJava.sql.ResultSet; Public classTest { Public StaticString sql = ""; Public StaticDBHelper db =NULL; Public StaticRESULTSET ret =NULL; Public Static voidMain (string[] args) {//TODO auto-generated Method StubString sql = "SELECT * FROM book"; DB=Newdbhelper (SQL); Try{ret=Db.pst.executeQuery (); while(Ret.next ()) {intid = ret.getint (1); String name= Ret.getstring (2); System.out.println ("ID:" + ID + ", Name:" +name); } //Close the database connection when you are finished usingRet.close (); Db.close (); } Catch(Exception e) {e.printstacktrace (); } }}
View Code
Output the contents of the MySQL Database Book table:
Connect to MySQL database using JDBC