Java to MySQL database operation under eclipse

Source: Internet
Author: User
Tags stmt

1. Download the MySQL driver.

link:http://dev.mysql.com/downloads/connector/j/

2. Load JDBC

In eclipse, select the appropriate project, Properties->java Build path->add external Jars->ok.

3.JDBC General steps to operate a database

Registered driver (only once) Class.forName ("Com.mysql.jdbc.Driver"); Establish connection (Connection) Connection conn = drivermanager.getconnection (URL, user, password); URL format: JDBC: Sub-Protocol: Sub-name//hostname: Port/database name? Property name = attribute value &. User,password can tell the database with the property name = attribute value; Example:

String url= "Jdbc:mysql://localhost:3306/test";

Connection Conn;

conn = drivermanager.getconnection (URL, "root", "root"), create Execute SQL statement (Statement) EXECUTE statement Statement is a SQL executor, Can be used to execute a static SQL statement. Statement st = Conn.createstatement (); st.executequery (SQL); Example

Statement stmt = Conn.createstatement (); Create a statement object
String sql= "SELECT * from writers";
ResultSet rs = stmt.executequery (SQL);

Execute stored procedure callablestatement (extended from preperedstatement) cs = Connection.preparecall ("{Call Psname (?,?,?)}"); Cs.registeroutparameter (index, Types.integer); Cs.setxxx (i, XXXX); cs.executeupdate (); int id=cs.getint (index); The processing execution result (ResultSet) ResultSet represents a query result set. ResultSet rs = statement.executequery (SQL); while (Rs.next ()) {rs.getstring ("Col_name"), Rs.getint ("Col_name"),//...} Release resources in order to release resources is ResultSet, statement,connection;connection after use is completed, must be closed, ResultSet, Statement does not matter, as long as Connection off, They are also automatically closed (but resources are not immediately released). Connection's use principle is to create as late as possible, releasing as early as possible.

Java to MySQL database operation under eclipse

Related Article

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.