Java Connection JDBC Section

Source: Internet
Author: User

To connect to a database step:
A. Using a Java program to establish a connection (channel) with a DB
B. Gets an object that executes an SQL statement based on the connection
C. Execute SQL statement
D. Close connection
public class Main {
public static void Main (string[] args) {
try {
1 Loading the driver class
Forname () Returns the class object associated with the classes or interfaces with the given string name
Class.forName ("Org.gjt.mm.mysql.Driver");

A. Establishing a connection channel
DriverManager manages a set of basic services for a JDBC driver. java.sql
Getconnection () Return: Connection to URL
String url= "Jdbc:mysql://127.0.0.1:3306/a11";
String user= "root";
String password= "root";
Connection conn=drivermanager.getconnection (URL, user,password);

B. Gets an object that executes the SQL statement
The Statement is used to execute a static SQL statement and return the object to which it produces results.
Createstatement () Creates a Statement object to send the SQL statement to the database.
Statement St;
St=conn.createstatement ();

C. Executing SQL statements
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement, or do not return content
St.executeupdate ("INSERT into student (Stuname,stuage,stusex,stubirth) VALUES (' Zhang San ', ' Ten, ' m ', ' 1988-08-09 ')");

D. Closing the connection
Immediately frees the database and JDBC resources for this Connection object, rather than waiting for them to be freed automatically
Conn.close ();
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
SYSTEM.OUT.PRINTLN ("Load Driver class failed!") ");
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

}
}

or close write in finally

Java Connection JDBC Section

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.