A summary of database instance based on JDBC Connection in Java development _java

Source: Internet
Author: User
Tags stmt

This article illustrates the method of database connection based on JDBC in Java development. Share to everyone for your reference, specific as follows:

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{
//loading 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 a successful load, an instance of the driver class is registered to the DriverManager class.

2. Provide the URL of the JDBC connection

A connection URL defines a protocol, a child protocol, and a data source identity when connecting to a database.

Writing form: Protocol: Sub-Protocol: Data source identification
Protocol: Always start with JDBC in JDBC
Sub-Protocol: The driver for the bridge connection or the name of the database management system.
Data source ID: Tag to locate the address and connection port of the database source.

For example: (MySQL's connection URL)

Jdbc:mysql:
LOCALHOST:3306/TEST?USEUNICODE=TRUE&CHARACTERENCODING=GBK;

Useunicode=true: Indicates the use of the Unicode character set. If Characterencoding is set to
gb2312 or GBK, this argument must be set to true. CHARACTERENCODING=GBK: Character encoding method.

3, create the connection of the database

To connect to a database, you need to request the Java.sql.DriverManager and get the Connection object, which represents a connection to a database.

Use the DriverManager getconnectin (string URL, string username, string password) method to obtain the path to the specified database to connect to, the user name and password of the database.

For example:

Connect 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

To execute the SQL statement, you must obtain the Java.sql.Statement instance, which is divided into the following 3 statement instances
Types of:

1, execute 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): Executes the SQL statement that queries the database, returns 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

Two cases:

1, the execution of the update returns 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 a set of get methods that provide the
Access to data in the row.

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 Object

After the operation is complete, all JDBC objects used are closed to release the JDBC resource, in reverse order and in the declaration order:

1, close the recordset
2. Close the statement
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 ();
 }
}

Supplemental: JDBC Connection Oracle Database sample

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
  public class Testoracle {public static void main (string[] args) {Connection conn = null;
  Statement stmt = null;
  ResultSet rs = null; try {class.forname ("oracle.jdbc.driver.OracleDriver");//Instantiate Oracle Database driver (build middleware) String URL = "Jdbc:oracle:thin: @loc Alhost:1521:oar92 ";//@localhost is the server name, Sjzwish is the database instance name conn = drivermanager.getconnection (URL," Guchao "," Jimmy "); Connection database, a for account, a for password stmt = conn.createstatement ();//Submit SQL statements, create a statement object to send SQL statements to the database//query data with executequery RS = s Tmt.executequery ("SELECT * from Ruby");//Execute Query, (Ruby) the table name while (Rs.next ()) {//Make the current record pointer navigate to the first record of the Recordset System.out.println (
   Rs.getstring ("Sid") + "" + rs.getstring ("sname"));
   }//1 represents the value of the first field in the current record, and can be written as a field name.
   2 represents the value of the second field in the current record, which can be written as a field name.
   Add Data with executeupdate//stmt.executeupdate ("INSERT into SS values (7, ' Jacky ')"); Modify data with Executeupdate//stmt.exeCuteupdate ("update SS Set name = ' Maggie ' WHERE id = 5");
  Delete data with executeupdate//stmt.executeupdate ("delete from SS where id = 6");
  catch (SQLException e) {e.printstacktrace ();
  catch (ClassNotFoundException e) {e.printstacktrace ();
   }finally{try {//Close database, End process rs.close ();
   Stmt.close ();
   Conn.close ();
   catch (SQLException e) {e.printstacktrace (); }
  }
 }
}

I hope this article will help you with your Java programming.

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.