Java connects to MySQL database and creates tables

Source: Internet
Author: User
Tags stmt

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.