JDBC Connection database code and steps in full Java development

Source: Internet
Author: User
Tags stmt
Create a program that connects the database with JDBC, which contains 7 steps: 1. Load JDBC Driver:Before connecting to a database, you first load the drive to the JVM (the Java Virtual machine) of the database you want to connect to, which is implemented by the static method forname (String className) of the Java.lang.Class class. For example:

try {
Load MySQL driver class
Class.forName ("Com.mysql.jdbc.Driver");
catch (ClassNotFoundException e) {
System.out.println ("Driver class not found, load driver failed." ");
E.printstacktrace ();
After successful loading, an instance of the driver class is registered to the DriverManager class.2. Provide the URL of the JDBC connection? The connection URL defines the protocol, the Child Protocol, and the data source identity when connecting to the database.? Write form: Protocol: Sub-Protocol: Data Source identification protocol: Always start with JDBC in JDBC: A bridge-connected driver or database management system name.        Data source ID: Tag to locate the address and connection port of the database source. For example: (Oracle's connection URL) jdbc:oracle:thin:@127.0.0.1:1521:orcl3, create the connection of the database? To connect to the database, you need to request the Java.sql.DriverManager and get the Connection object, which represents a connection to a database.? use drivermanager getconnectin (String ur         The L, string Username, string password method is obtained by passing in the path of the specified database to which you want to connect, the username and password of the database. For example:

Connect to MySQL database, username and password are root
String url = "Jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root";
try {
Connection con = drivermanager.getconnection (URL, username,
password);
catch (SQLException se) {
SYSTEM.OUT.PRINTLN ("Database connection failed.") ");
Se.printstacktrace ();
4, create a statement statement object ? To execute an SQL statement, you must obtain a java.sql.Statement instance, and the statement instance is divided into the following 3 types: 1, executing a static SQL statement 。          Typically implemented through statement instances. 2, execute dynamic SQL statements.          Typically implemented through PreparedStatement instances. 3, execute the database stored procedure.        Typically implemented through CallableStatement instances. Specific ways to achieve:

Statement stmt = Con.createstatement ();
PreparedStatement pstmt = con.preparestatement (sql);
CallableStatement cstmt = Con.preparecall ("{Call Demosp (?,?)}");     5. Execute SQL statement The statement interface provides three ways to execute SQL statements: ExecuteQuery, Executeupdate, and execute 1, ResultSet executequery (String sqlstring): Executing         Queries the SQL statement of the database, returning a result set (ResultSet) object.         2, int executeupdate (String sqlstring): Used to execute INSERT, UPDATE, or DELETE statements and SQL DDL statements, such as CREATE table and drop table       3. Execute (sqlstring): Used to execute statements that return multiple result sets, multiple update counts, or combinations of both. Specific code to implement:

ResultSet rs = stmt.executequery ("SELECT * from ...");
int rows = Stmt.executeupdate ("INSERT into ...");
Boolean flag = Stmt.execute (String sql);
6, processing results of two cases: 1, the implementation of the update returned is the number of records affected by this operation. 2. The result returned by the execution query is a ResultSet object. ResultSet contains all the rows that conform to the conditions in the SQL statement, and it provides access to the data in those rows through a set of Get methods. Get data using the access method of the result set (ResultSet) object:

while (Rs.next ()) {String name = rs.getstring (' name '); String pass = rs.getstring (1); This method is more efficient} (columns are numbered from left to right, and starting from column 1) 7. Close JDBC ObjectAfter the operation is complete, all the JDBC objects used will be closed to release the JDBC resource, in reverse order and in the declaration order: 1, close Recordset 2, close the Declaration 3, close the Connection object

if (Rs!= null) {//close Recordset
try {
Rs.close ();
catch (SQLException e) {
E.printstacktrace ();
}
}
if (stmt!= null) {//Close declaration
try {
Stmt.close ();
catch (SQLException e) {
E.printstacktrace ();
}
}
IF (conn!= null) {//Close Connection object
try {
Conn.close ();
catch (SQLException e) {
E.printstacktrace ();
}
}

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.