JDBC Database programming

Source: Internet
Author: User
Tags heidisql

*********************************************** Declaration *********************** *******************************

Original works, from the "Xiaofeng Moon XJ" blog, Welcome to reprint, please be sure to indicate the source (HTTP://BLOG.CSDN.NET/XIAOFENGCANYUEXJ).

Due to various reasons, there may be many shortcomings, welcome treatise!

*************** ******************************************************************************************

recently in the self-taught MySQL database, while the future development language in the workplace is Java, so try to write a small transaction database program in the Eclipse environment. Talk about the development of Java MySQL database applications here. You should first install the MySQL database on the local machine, the installation process see the link provided by the Novice on the road, and then it is best to install the Auxiliary visualizer: Heidisql, the specific process is provided in the Heidisql article links. Each other is the MySQL JDBC driver installation, which provides a link here: MySQL jdbc driver.

Follow the above steps, the rest is the application of the writing, JDBC programming in the relevant process is generic, should focus on the look, here I talk about my understanding.

Jdbc:java database connection. JDBC is a set of programming interfaces that are implemented by the underlying developers of the database system, and Java developers invoke the interfaces provided by JDBC to create, link, update, and manipulate the database. JDBC provides two APIs, namely the developer-oriented API and the JDBC driver API for the underlying, which is primarily connected to the database through direct JDBC driver and Jdbc-odbc bridge drivers.
1), load the database driver;

Class.forName (Driver)//Here driver refers to the path of the drive

2), establish database connection;

Connection con = drivermanager.getconnection (url, user, password);//access the specified database with a specific user

3), Operation database, execute SQL statement;

4), disconnect the database.


Here is a brief introduction to the JDBC Connection database code and steps in full Java development, where we would like to express our gratitude:

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), 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 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: Tag finds the address and connection port of the database source.
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.   
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.
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
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 (?,?)}");   
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 perform statements that return multiple result sets, multiple update counts, or a combination of 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), perform the update returns the number of records affected by this operation.
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 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 start with column 1)   
7. Close the JDBC Object
After the operation is complete, all the JDBC objects used are closed to release the JDBC resource, and the order of closing and declaration is reversed:
1), close record set
2), close the Declaration
3), close Connection object-database

     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) {  //Closes the Connection object            try{               conn.close ();            } catch (SQLException e) {               e.printstacktrace ();            }           

The above paragraph of the text introduced very good, and I am also a beginner, on the direct reprint, in this expressed thanks! The following affixed to my entry-level code, to graduate, immediately to work, want to contact a bit of work may be used to get the JDBC database development, there is no time to write a very large project, so just describe the general process, laughed at!

Import java.sql.*;p Ublic class Jdbcdemo {public static void main (string[] args) {String user = "root"; String password = "199203211410xfcy"; String url = "Jdbc:mysql://localhost:3306/studentdb";//establish the address of the database server string tableName = "Student_information"; String Driver = "Com.mysql.jdbc.Driver"; String sqlsentence; Connection con = null;//Connection object Statement stmt = null;//Operation Object ResultSet rs = null;//query result try {class.forname (driver);// Load the database driver driver class con = drivermanager.getconnection (url, user, password);//database connection to access the specified database with a specific user stmt = Con.createstatement (); sqlsentence = "INSERT INTO" + TableName + "VALUES (9, ' honey ', +)"; Stmt.executeupdate (sqlsentence ); sqlsentence = "SELECT * from" + Tablename;rs = stmt.executequery (sqlsentence); ResultSetMetaData RSMD = Rs.getmetadata (); int j = 0;j = Rsmd.getcolumncount (); for (int k = 0; k < J; k++) {SYSTEM.OUT.P Rint (Rsmd.getcolumnname (k + 1)); System.out.print ("\ t");} System.out.println (); while (Rs.next ()) {for (int i = 0; i < J; i++) {System.out.print (rs.getstring (i + 1)); System.out.print ("\ t");} System.out.println ();}} catch (ClassNotFoundException E1) {System.out.println ("database driver does not exist!") "); System.out.println (E1.tostring ());} catch (SQLException E2) {System.out.println ("the database has an exception! "); System.out.println (E2.tostring ());}  Finally {try {if (rs! = null) rs.close (); if (stmt! = null) stmt.close (); if (con! = null) Con.close ();} catch (SQLException e) {System.out.println (e.tostring ());}}}}
The premise is to have a STUDENTDB database, and a student_information table with a consistent attribute.


Due to the limited time, in the process of writing a few references to some of the literature, thank you, at the same time, given the level of reasons, you inevitably have shortcomings, welcome treatise!







JDBC Database 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.