Java programs connect to MySQL database

Source: Internet
Author: User
Tags stmt

(1) Call the Class.forName () method to load the appropriate database driver

Class.forName ("Com.mysql.jdbc.Driver");

(2) Call the Drivermanager.getconnection () method to obtain a connection object that represents an open connection

Connection conn = drivermanager.getconnection (URL, username, password);

(3) Use the Connection.createstatement () method to create a statement statement object that passes simple SQL statements without arguments to the database management system for execution

Statement stmt = Conn.createstatement ();

Use the Connection.preparestatement () method to create a PreparedStatement statement object that passes an SQL statement with one or more input parameters

Preparestatement PSM = conn.preparestatement ("INSERT into book (BookID, Name) VALUES (?,?)");

Use the Connection.preparecall () method to create a CallableStatement statement object that calls the stored procedure

CallableStatement CSM = Conn.preparecall ("{Call validate (?,?)}"); –validate is the name of the stored procedure

(4) EXECUTE statement

Execute Query statement

ResultSet rs = stmt.executequery (SQL);

Executing DML statements (that is, insert, UPDATE, DELETE)

int n = stmt.executeupdate (sql);

The Execute () method can execute both of these SQL statements

(5) Handling ResultSet objects

while (Rs.next ()) {

Rs.getstring (1);

......

}

(6) Close the connection

Rs.close ();

Stmt.close ();

Conn.close ();

Java programs connect to MySQL database

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.