1 Create a new Java Project named Mysqldemo
2 Download the latest driver package from http://dev.mysql.com/downloads/connector/j/.
Here are the. tar.gz and. zip Two-format packages, because they can be decompressed under Windows, either way.
3 after extracting the downloaded drive package, copy the Mysql-connector-java-5.1.38-bin.jar to the project
4 Creating a Java class named Mysqldemo in the project
5 Writing code in Mysqldemo.java
[Java]View PlainCopy
- Package com.abc;
- Importjava.sql.DriverManager;
- Importjava.sql.ResultSet;
- Importjava.sql.SQLException;
- Importjava.sql.Connection;
- Importjava.sql.Statement;
- Publicclass Mysqldemo {
- Publicstaticvoid Main (string[] args) throws Exception {
- Connection conn = null;
- String SQL;
- //MySQL JDBC URL writing method: jdbc:mysql://Host Name: Connection port/database name? parameter = value
- //Avoid Chinese garbled to specify Useunicode and characterencoding
- String url = "Jdbc:mysql://localhost:3306/test?"
- + "User=root&password=123456&useunicode=true&characterencoding=utf8";
- try {
- //The reason to use the following statement is to use the MySQL driver, so we have to drive it up,
- //Can be loaded through the class.forname, can also be driven by initialization, the following three forms can be
- Class.forName ("Com.mysql.jdbc.Driver"); Dynamic load MySQL driver
- //or:
- //Com.mysql.jdbc.Driver Driver = new Com.mysql.jdbc.Driver ();
- //or:
- //New Com.mysql.jdbc.Driver ();
- System.out.println ("load MySQL driver successfully");
- //A connection represents a database connection
- conn = drivermanager.getconnection (URL);
- //Statement with many methods, such as executeupdate can be inserted, update and delete, etc.
- Statement stmt = Conn.createstatement ();
- sql = "createtable student (no char (), name varchar (), primary key (No))";
- Intresult = stmt.executeupdate (sql); the///Executeupdate statement returns an affected number of rows if the return-1 does not succeed
- if (Result! =-1) {
- System.out.println ("Create data Table Success");
- sql = "INSERT into student (No,name) VALUES (' 2016001 ', ' Liu Big ')";
- result = Stmt.executeupdate (SQL);
- sql = "INSERT into student (No,name) VALUES (' 2016002 ', ' Chen er ')";
- result = Stmt.executeupdate (SQL);
- sql = "SELECT * from student";
- ResultSet rs = stmt.executequery (SQL); //ExecuteQuery Returns a collection of results, otherwise returns a null value
- System.out.println ("School number \ t name");
- While (Rs.next ()) {
- System.out.println (rs.getstring (1) + "\ T" + rs.getstring (2)); If the type int is returned can be used Getint ()
- }
- }
- } catch (SQLException e) {
- System.out.println ("MySQL operation Error");
- E.printstacktrace ();
- } catch (Exception e) {
- E.printstacktrace ();
- } finally {
- Conn.close ();
- }
- }
- }
Operation Result:
JDBC Pure Drive mode connection MySQL