Java JDBC Connection database access connection database

Source: Internet
Author: User
Tags odbc stmt

1. Load the JDBC driver:

Before connecting to a database, you first load the driver of the database you want to connect to the JVM (Java Virtual Machine), and then implement it through 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 a successful load, an instance of the driver class is registered in the DriverManager class.

2. Provide the URL of the JDBC connection

    • The connection URL defines the protocol, sub-protocol, and data source identity when the database is connected.
    • Writing form: Protocol: Sub-Protocol: Data source identification

Protocol: Always start with JDBC in JDBC

Sub-Protocol: A bridge-connected driver or database management system name.

Data source identification: The tag locates the address of the database source and the connection port.

For example: (MySQL 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 parameter must be set to true .

CHARACTERENCODING=GBK: The character encoding method.

Connection URL for SQL Server

Jdbc:microsoft:sqlserver://localhost:1433;databasename=dbname

Bridge connection

The URL represents the location of the data source that needs to be connected, at which point the connection to the Jdbc-odbc bridge is used, and the URL is "JDBC:ODBC: Data Source Name"
String url = "Jdbc:odbc:StudentManger";

3. Create a connection to the database

    • To connect to a database, you need to request and obtain a connection object from Java.sql.DriverManager, which represents a connection to a database.
    • The DriverManager getconnectin (string URL, string username, string password) method is used to pass in the path of the specified database to be connected, the user name of the database, and the password to obtain.

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

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

1. Execute static SQL statements. 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.

The specific implementation method:

Statement stmt = Con.createstatement ();

PreparedStatement pstmt = con.preparestatement (sql);

CallableStatement cstmt =con.preparecall ("{Call Demosp (?,?)}");//This has not been used for the time being.

5. Execute SQL statements

    • 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 and 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, etc.

3. Execute (sqlString): Used to execute statements that return multiple result sets, multiple update counts, or both.

Specific implementation code:

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 number of records affected by this operation is returned by performing the update.

2. The result of executing the query returned is a ResultSet object.

? ResultSet contains all rows that conform to the conditions in the SQL statement, and it provides a set of get methods for these

Access to the data in the row.

? Get data using the access method of the result set (ResultSet) object:

while (Rs.next ()) {

String name = rs.getstring ("name"); Column Name

String pass = rs.getstring (1); This method is more efficient

}

Note: The column is numbered from left to right, and the column 1 Start

7 , close the JDBC object

All JDBC objects used are closed after the operation is complete to release the JDBC resource, turn off order harmony

The opposite of the Ming Order:

1. Close record set

2. Closing 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.prints Tacktrace ();            }        }

Connect to access data

1. Data source (ODBC)

Data sources (ODBC), management tools, control Panel, system security

Second, to add the Rt.jar to MyEclipse Lib, because Rt.jar has sun.jdbc.odbc.driver. If your computer has a JDK, then in the JDK Lib find out if there is no rt.jar, if there is no JDK, go to the online next JDBC:ODBC driver package, let the MyEclipse in the Lib.
Added classpath in the environment variable later, the path is the absolute path of the driver package, such as the c:myeclipse/lib/driver package name. jar, after adding, you need to restart your computer, then you can connect.

Here are a few of my programs:

Package Com.javen.jdbc;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.ResultSet;import Java.sql.statement;public class Jdbctest {public    static void Main (string[] args) {        //URL indicates the location of the data source that needs to be connected, At this point, the connection method of Jdbc-odbc bridge is used, the URL is "JDBC:ODBC: Data Source name"        String url = "Jdbc:odbc:StudentManger";        try {            class.forname ("Sun.jdbc.odbc.JdbcOdbcDriver");            Connection conn = drivermanager.getconnection (URL);            Statement stat = conn.createstatement ();            String sql = "SELECT * from Student";            ResultSet rs = stat.executequery (sql);            while (Rs.next ()) {                System.out.println (rs.getstring (2))}        } catch (Exception e) {            //TODO Auto-generated Catch block            e.printstacktrace ();}}    

Java JDBC Connection database access connection database

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.