Connect Java to mysql database and javamysql Database
Tool: eclipse
Mysql database
Jar package used: mysql-connector-java-5.1.27.jar
Create sqldemo
After downloading the jar package, create a new lib folder in the demo to store the jar package. Right-click demo Build Path to add jar package
Database Configuration to create an emp employee table. Fields include ID, ename, job, hiredate, and sal. Insert some information
My database is sqltestdb. User: root Password 123
Create a class.
Package sqldemo; import java. SQL. driverManager; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; import com. mysql. jdbc. connection; public class mian {public static void main (String [] args) {// declare the Connection object Connection con; // driver name String driver = "com. mysql. jdbc. driver "; // point to the name of the database to be accessed sqltestdb String url =" jdbc: mysql: // localhost: 3306/sqltestdb "; // user name String user =" root "; // Password String password = "123"; // traverse the query result set try {// load the program Driver Class. forName (driver); // The getconnection method connects to the database con = (Connection) DriverManager. getConnection (url, user, password); if (! Con. isClosed () {System. out. println ("database connected");} // create a sta to execute the SQL Statement sta = con. createStatement (); // The SQL statement to be executed String SQL = "select * from emp"; // 3. the ResultSet class, used to store the obtained result set !! ResultSet rs1_sta.exe cuteQuery (SQL); System. out. println ("-----------------"); System. out. println ("the execution result is 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 ("data retrieved ");}}}
The result set printed in the background is:
This operation is mainly performed on the Connection object. Create it to add, delete, modify, and query data in the database. To configure your username and password, the configuration in the Code must be the same as the actual database configuration.