JDBC database programming and jdbc programming books

Source: Internet
Author: User
Tags heidisql

JDBC database programming and jdbc programming books

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

Original works, from the "Xiaofeng residual month xj" blog, welcome to reprint, reprint please be sure to indicate the source (http://blog.csdn.net/xiaofengcanyuexj ).

For various reasons, there may be many shortcomings. Thank you!

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

I recently learned how to use MySQL Databases and how to develop Java in the workplace. So I tried to write a database program for small transaction processing in the eclipse environment. Here we will talk about the development of Java MySQL database applications. First, you should install the MySQL database on the local machine. For details about the installation process, see the link provided by the novice. Then, install the auxiliary visual tool HeidiSQL. For details, see the link provided in HeidiSQL. However, the installation of the MySQL JDBC driver is the same as that of the MySQL JDBC driver. Here is a link: MySQL JDBC driver.

According to the above steps, the rest is the compilation of the application program, and the relevant procedures in JDBC programming are generic. Let's take a look at it. Here I will 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. Java developers call the interfaces provided by JDBC to create, link, and update databases. JDBC provides two types of APIS, namely for developers and for the underlying JDBC driver API, the underlying mainly through direct JDBC driver and JDBC-ODBC bridge driver to achieve the connection with the database.
1) load the database driver;

Class. forName (driver) // The driver path.

2) Establish a database connection;

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

3) operate the database and execute SQL statements;

4) disconnect the database.


The following is a brief introduction. I would like to express my gratitude for the complete code and steps for connecting to the database through JDBC in java Development:

1. Load the JDBC driver:
Before connecting to the database, load the driver of the database to be connected to JVM (java Virtual Machine), which is achieved through the static method forName (String className) of java. lang. Class.
For example:

Try {// load the MySql Driver Class. forName ("com. mysql. jdbc. driver ");} catch (ClassNotFoundException e) {System. out. println ("The driver class cannot be found. Failed to load the driver! "); E. printStackTrace ();}
After the Driver class is loaded, the Driver class instance is registered to the DriverManager class.
2. Provide the URL of the JDBC connection
The connection URL defines the protocol, sub-protocol, and data source identification used to connect to the database. Writing format: Protocol: Sub-Protocol: data source identifier; Protocol: Always starting with JDBC in jdbc; Sub-Protocol: the name of the Bridge Connection driver or database management system; data source identifier: mark the address and connection port of the database source.
Example: (MySql connection URL)

Jdbc: mysql: /// localhost: 3306/test? UseUnicode = true & characterEncoding = gbk; useUnicode = true: indicates that the Unicode character set is used. If characterEncoding is set to gb2312 or GBK, this parameter must be set to true. CharacterEncoding = gbk: character encoding method.
3. Create a database connection
To connect to the database, you need to request to java. SQL. DriverManager and obtain the Connection object. This object represents the Connection to a database. Use the getConnectin (String url, String username, String password) method of DriverManager to input the path of the database to be connected, and the username and password of the database.
For example:
// Connect to the MySql database. The username and password are both 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 an SQL Statement, you must obtain a java. SQL. Statement instance. The following three types of Statement instances are available:
1) execute static SQL statements. It is usually implemented through a Statement instance.
2) execute dynamic SQL statements. It is usually implemented through the PreparedStatement instance.
3) execute the database storage process. It is usually implemented through the CallableStatement instance.
Specific implementation methods:
       Statement stmt = con.createStatement() ;          PreparedStatement pstmt = con.prepareStatement(sql) ;          CallableStatement cstmt = con.prepareCall("{CALL demoSp(? , ?)}") ;   
5. Execute SQL statements
The Statement interface provides three methods for executing SQL statements: executeQuery, executeUpdate, and execute.
1) ResultSet executeQuery (String sqlString): Execute the SQL statement to query the database and return a result set 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): it is used to execute statements that return multiple result sets, multiple update counts, or a combination of the two.
Specific implementation code:
    ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;       int rows = stmt.executeUpdate("INSERT INTO ...") ;       boolean flag = stmt.execute(String sql) ;   
6. processing result
Two cases:
1) the number of records affected by this operation is returned when an update is executed.
2) The result returned by executing the query is a ResultSet object.
The ResultSet contains all rows that meet the conditions in the SQL statement, and provides access to the data in these rows through a set of get methods. Use the access method of the result set object to obtain data:
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 from column 1)
7. Disable JDBC objects
After the operation is complete, you need to close all the used JDBC objects to release the JDBC resources. The order of closure is the opposite of the declared order:
1) Disable record set
2) Close the statement
3) Close the connection object-Database

If (rs! = Null) {// close record set try {rs. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (stmt! = Null) {// close the Declaration try {stmt. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (conn! = Null) {// close the connection object try {conn. close () ;}catch (SQLException e) {e. printStackTrace ();}}

The text above is quite good, and I am also a beginner. I will reprint it directly. Thank you! Next I will post a piece of my entry-level code. After graduation, I am about to work. I want to have more access to the JDBC database development that can be used at work. Do I have time to write a large project, so I just described the general process and laughed!

Import java. SQL. *; public class JDBCDemo {public static void main (String [] args) {String user = "root"; String password = "199203211410 xfcy"; String url = "jdbc: mysql: // localhost: 3306/studentdb "; // 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. for Name (driver); // load the database Driver Class con = DriverManager. getConnection (url, user, password); // database connection, which allows a specific user to access the specified database stmt = con. createStatement (); sqlSentence = "insert into" + tableName + "values (9, 'Honey ', 21)" ;stmt.exe cuteUpdate (sqlSentence ); sqlSentence = "select * from" + tableName; rs = stmt.exe cuteQuery (sqlSentence); ResultSetMetaData rsmd = rs. getMetaData (); int j = 0; j = rsmd. getColumnCount (); for (I Nt k = 0; k <j; k ++) {System. out. print (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 ("the 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 the same attributes.


Due to limited time, I have referenced some documents during the blog writing process and would like to express my gratitude. In addition, you may have some shortcomings due to the level. Thank you!







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.