Tools: Eclipse
MySQL Database
Jar Package used: Mysql-connector-java-5.1.27.jar
Create Sqldemo
After the jar package is downloaded, create a new Lib folder in the demo to hold the jar package. Right-click Demo Build path to add jar package
Database configuration, create a new EMP employee table. Field has id,ename,job,hiredate,sal. Insert some information
My database is sqltestdb. User: root password: 123
Create a class.
PackageSqldemo;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;Importcom.mysql.jdbc.Connection; Public classMian { Public Static voidMain (string[] args) {//declaring connection ObjectsConnection con; //driver nameString driver= "Com.mysql.jdbc.Driver"; //point to the name of the database you want to access SqltestdbString url= "Jdbc:mysql://localhost:3306/sqltestdb"; //User nameString user= "Root"; //PasswordString password= "123"; //traversing query result sets Try { //Loader driverClass.forName (driver); //getconnection Method Connection Databasecon=(Connection) drivermanager.getconnection (URL, user, password); if(!con.isclosed ()) {System.out.println ("Database is Connected"); } //create STA to execute SQL statementStatement Sta=con.createstatement (); //the SQL statement to executeString sql= "SELECT * from emp"; //3.ResultSet class, used to store the obtained result set!! ResultSet rs=sta.executequery (SQL); System.out.println ("-----------------"); System.out.println (The results of the execution are as follows:); System.out.println ("-----------------"); System.out.println ("Name" + "\ T" + "title"); System.out.println ("-----------------"); String Job=NULL; String ename=NULL; while(Rs.next ()) {Job=rs.getstring ("Job"); Ename=rs.getstring ("ename"); System.out.println (ename+ "\ T" +job); } rs.close (); Con.close (); } Catch(ClassNotFoundException e) {System.out.println ("Connection Exception"); }Catch(SQLException e) {e.printstacktrace (); }Catch(Exception e) {e.printstacktrace (); }finally{System.out.println ("Get Data Success"); } }}
The background print result set is:
This is mainly the operation of the Connection object. Create it to perform additions and deletions to the data in the database. To configure your own user name and password, the configuration in your code will be the same as your actual database configuration
Java Connection MySQL Database