Connect java to mysql database and javamysql Database
1. First download the mysql installation package, download the link mysql, and then install.
2. Enter the username and password for installation to connect to the database.
3. Install the mysq JDBCl driver in Eclipse. The installation steps are as follows:
Test whether mql is successfully connected. Code:
Package day_09; import java. SQL. *; public class Test {public static void main (String [] args) {String url = "jdbc: mysql: // localhost: 3306/mydb "; string user = "root"; String password = "281889"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try {Class. forName ("com. mysql. jdbc. driver "); conn = DriverManager. getConnection (url, user, password); stmt = conn. createStatement (); String SQL; SQL = "insert int O student values (2014218, 'Li Yue ', 'female') "; stmt.exe cute (SQL); SQL =" select * from student "; rs = stmt.exe cuteQuery (SQL ); system. out. println ("student ID" + "\ t" + "name" + "\ t" + "gender"); String name = null; while (rs. next () {name = rs. getString ("sname"); System. out. println (rs. getString ("sno") + "\ t" + name + "\ t" + rs. getString ("sex") ;}} catch (ClassNotFoundException e1) {System. out. println ("the database driver does not exist! "+ E1.toString ();} catch (SQLException e2) {System. out. println (" database exception "+ e2.toString ();} finally {try {if (rs! = Null) rs. close (); if (stmt! = Null) stmt. close (); if (conn! = Null) conn. close () ;}catch (SQLException e) {System. out. println (e. toString ());}}}}
Print result: