A preparatory work
1. The default user of this article has correctly installed MySQL, and to ensure that the service starts normally, you can use the related features of MySQL.
2. Download Mysql-connector-java.jar (link), unzip, the jar package introduced,:
3. Introduce the JAR package:
The basic environment is now configured.
Ii. establishing a database
1. Create a database.
CREATE DATABASE MY;
2. Create a student table.
CREATE TABLESTUDENT (SNOCHAR(7) not NULL, SNAMEVARCHAR(8) not NULL, SEXCHAR(2) not NULL, Bdate DATE not NULL, HEIGHTDEC(5,2)DEFAULT 000.00, PRIMARY KEY(SNO));
3. Insert the data yourself.
Three Run the test program
ImportJava.sql.*; Public classJdbctest { Public Static voidMain (string[] args) {//driver nameString Driver = "Com.mysql.jdbc.Driver"; String URL= "Jdbc:mysql://127.0.0.1:3306/student"; //user name when MySQL is configuredString user = "root"; //password for MySQL configurationString password = "root"; Try { //Load DriverClass.forName (driver); //Continuous DatabaseConnection conn =drivermanager.getconnection (URL, user, password); if(!conn.isclosed ()) System.out.println ("Succeeded connecting to the database!"); //statement used to execute SQL statementsStatement Statement =conn.createstatement (); //the SQL statement to executeString sql = "SELECT * FROM Student"; //result setResultSet rs =statement.executequery (SQL); System.out.println ("-----------------"); System.out.println (The results of the execution are as follows:); System.out.println ("-----------------"); System.out.println ("School Number" + "\ T" + "name"); System.out.println ("-----------------"); String name=NULL; while(Rs.next ()) {//Select sname This column of dataName = Rs.getstring ("sname"); Name=NewString (Name.getbytes ("iso-8859-1"), "GB2312"); //Output ResultsSystem.out.println (rs.getstring ("sno") + "\ T" +name); } rs.close (); Conn.close (); } Catch(ClassNotFoundException e) {System.out.println ("Sorry,can ' t find the driver!"); E.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } } }
Finish.
Java connection MySQL