Java Connection MySQL Database

Source: Internet
Author: User

Download MySQL database: http://dev.mysql.com/downloads/mysql/, unzip to local

Download jar package: http://dev.mysql.com/downloads/connector/j/, download zip archive package

Create a database and insert several data:

Create TableMyDB; UseMyDB;Create TableStudent (namevarchar(8), noChar(7));Insert  intoStudentValues('Zhang','011');Insert  intoStudentValues('Li','021');Select *  fromStudent

Database Connection class:

 PackageG.dao;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement; Public classDbConnection { Public StaticConnection getconnection ()throwsClassNotFoundException, SQLException {class.forname ("Com.mysql.jdbc.Driver"); String URL= "Jdbc:mysql://127.0.0.1:3306/mydb"; Connection Connection= Drivermanager.getconnection (URL, "root", "root"); returnconnection; }     Public Static voidFree (Connection Connection, Statement Statement, ResultSet ResultSet) {Try {            if(ResultSet! =NULL) {resultset.close (); }            if(Statement! =NULL) {statement.close (); }            if(Connection! =NULL) {connection.close (); }        } Catch(SQLException e) {e.printstacktrace (); }    }}

To test the JDBC connection:

 PackageG.dao;Importjava.sql.Connection;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException; Public classTESTJDBC { Public Static voidMain (string[] args) {Connection Connection=NULL; PreparedStatement Statement=NULL; ResultSet ResultSet=NULL; Try{Connection=dbconnection.getconnection (); String SQL= "SELECT * FROM Student"; Statement=connection.preparestatement (SQL); ResultSet=Statement.executequery ();  while(Resultset.next ()) {System.out.println (resultset.getstring ("Name") + ":" + resultset.getstring ("no"))); }        } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); }    }}

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.