Java link MySQL database requires a driver package, then we first download the driver package http://dev.mysql.com/downloads/connector/j/, The driver package is a jar package contains the class we want to use, Methods, etc.
。 To import the downloaded driver package into our project, we can write the program to create our table. Refer to the API documentation https://docs.oracle.com/javase/8/docs/api/overview-summary.html
1 ImportJava.sql.*;2 Public classLinksql {3 4 //I'm going to execute the DDL statement that created the table5 StaticString creatsql = "CREATE TABLE pepole ("6+ "name varchar (ten) NOT NULL,"7+ "Age int (4) is not NULL"8+ ") Charset=utf8;";9 Ten Final StaticString jdbc_driver = "Com.mysql.jdbc.Driver"; One //Specify the URL of the connection database A Final StaticString Db_url = "Jdbc:mysql://localhost/student"; - //MySQL user name - Final StaticString name = "Root"; the //mysql Password - Final StaticString pwd = "pwd"; - Public Static voidMain (string[] args) - { +Connection conn =NULL; -Statement stmt =NULL; + Try A { at //registering the JDBC driver - Class.forName (jdbc_driver); - //Open Connection -SYSTEM.OUT.PRINTLN ("//Connection database"); -conn =drivermanager.getconnection (db_url,name,pwd); - //Execute CREATE TABLE inSYSTEM.OUT.PRINTLN ("//CREATE TABLE"); -stmt =conn.createstatement (); to if(0 = =stmt.executelargeupdate (creatsql)) + { -SYSTEM.OUT.PRINTLN ("CREATE TABLE successfully!") "); the } * Else $ {Panax NotoginsengSystem.out.println ("Failed to create TABLE! "); - } the// + stmt.close (); A conn.close (); theSYSTEM.OUT.PRINTLN ("//Close Resources"); + } - Catch(Exception e) $ { $System.out.println ("Failed to create TABLE! "); - e.printstacktrace (); - } the } - }Wuyi
Java connects to MySQL database and creates tables