JDBC Basics Tutorial _java

Source: Internet
Author: User

This example describes the basics and techniques of JDBC. Share to everyone for your reference. The specific analysis is as follows:

1. What is JDBC?

In general, the JDBC technology is through the Java program to send SQL statements to the database, the database received SQL statements after the execution, the results returned to the Java program management.

2. What are the conditions for using JDBC?

A the address of the target database host

B the port number that the database software occupies on the host

C the user name used to log in to the database

D) The password for the username

E) connecting to the database

The principle of 3.JDBC technology

We know that there are various types of databases, the different manufacturer's database standard and the specification are different, this time, if we use the Java code to send the SQL statement, must according to the different database to write one set of operation code, this to the program developer's development cost is very huge, therefore, When the company was developing JDBC technology, sun A set of standard interfaces, the database vendor must provide a driver to implement the interface, so long as the program developers in the development of the use of the database driver, it is a consistent approach to development, without the need to write a set of code to adapt to different databases.

The core API in 4.JDBC

|-Driver: interface implemented by driver class.

|-connection Connect (String URL, Properties info)--for connecting to the database, getting the connection object

Parameters to be set in Properties:

URL: The URL string for the database connection. Protocol + Database Sub-protocol + host + port + database

User: Database username

Password: User's password

|-connection: Interfaces connected to the database

|-Statement createstatement ()--Create Statement object for sending SQL statements

|-PreparedStatement preparestatement (String sql)-Create PreparedStatement object for sending precompiled SQL statements

|-callablestatement preparecall (String sql)-Creates a CallableStatement object to invoke a stored procedure.

|-statement: Used to execute static SQL statements

|-int executeupdate (String sql)--Perform the update operation (DDL+DML)

|-resultset executequery (String sql)--performing a query operation (DQL)

|-preparedstatement: SQL statements for performing precompilation

|-int executeupdate ()--Perform update operations

|-ResultSet executequery ()--Perform query operations

|-callablestatement: SQL for executing stored procedures

|-ResultSet executequery ()-Calling stored procedures

|-ResultSet: result set. Data after the query used to encapsulate the database

| |-Boolean NEXT ()--Move the record cursor to the next line

| |-Object getObject (int columnindex)--Get the value on the field

After you know what APIs, let's use JDBC to send SQL statements.

5. Manipulate the database using the statement object

DDL and DML operations

Step 1

Guide package, because I am using the MySQL database, so to use the JDBC technology, you must use the database driver provided by the MySQL database, so the first step is to import the database driver package into the project.

Package name to use: Mysql-connector-java-5.1.7-bin.jar

Step 2

Create a normal class, add a method inside, and follow these steps in the method

Copy Code code as follows:
Url


Private String URL = "Jdbc:mysql://localhost:3306/vmaxtam";


User


Private String user = "root";


Password


Private String Password = "root";

public void Testddl () throws exception{


1. Registration Driver


Class.forName ("Com.mysql.jdbc.Driver");





2. Get connection


Connection conn = drivermanager.getconnection (URL, user, password);





3. Create a statement object


Statement stmt = Conn.createstatement ();





4. Prepare SQL statements


String sql = "CREATE TABLE student (SID int PRIMARY Key,sname VARCHAR (), age int)";





5. Send SQL statement via Statement object, return execution result


int count = stmt.executeupdate (SQL);





6. Print execution results


System.out.println ("Affects the" +count+ "record");


}


7. Closing Resources


if (statement!=null)


{


Statement.close ();


}

if (conn!=null)
{
Conn.close ();
}




If you want to perform DQL and DDL operations, you can write the SQL statement, and then call the statement Executlupdate method to execute the SQL statement to the database, which returns an integer value indicating how many rows in the database are affected.

If we do not change the above program, want to send SQL statements to the database, then write a program to connect again, after the operation to close the statement object and connection object, this is very tedious. So, we typically extract the connection process and the process of releasing the object into a tool class. The code in the tool class is as follows:

Copy Code code as follows:
public class Sqlutil {


private static String URL = "Jdbc:mysql://localhost:3306/vmaxtam";


private static String user = "root";


private static String password = "root";

Get connection


public static Connection getconnection () {


Connection conn = null;


try {


1. Registration Driver


Class.forName ("Com.mysql.jdbc.Driver");


2. Get connection


conn = drivermanager.getconnection (URL, user, password);


3. Access to statement objects


Statement Statement = Conn.createstatement ();


catch (Exception e) {


TODO auto-generated Catch block


E.printstacktrace ();


}


Return conn;


}

7. Closing Resources


public static void Close (Statement Statement, Connection Connection) {


{


try {


if (statement!= null)


Statement.close ();


if (connection!= null) {


Connection.close ();


}


catch (SQLException e) {


TODO auto-generated Catch block


E.printstacktrace ();


}


}


}


}

The other thing to consider is:

A user only need to register a drive on the line, without each connection database are registered driver, so we put the registration-driven process written in the static code block.

Second, URL and username, password and driver class name, in the program is written dead, in order to be able to change the code under the premise of replacing the database or change the user, we usually write this information to a configuration file.

The configuration file is written in the SRC directory of the project, named Db.properties

Copy Code code as follows:
Url=jdbc:mysql://localhost:3306/vmaxtam
User=root
Password=root
Driverclass=com.mysql.jdbc.drive



Then read the configuration file in Sqlutil and finally optimize to the following code


Copy Code code as follows:
public class Sqlutil {


private static String URL = null;


private static String user = null;


private static String password = NULL;


private static String driverclass= null;

static{


try {


1. Get byte code object


Class clazz = Sqlutil.class;





2. Call getResourceAsStream Fetch path


InputStream InputStream = Clazz.getresourceasstream ("/db.properties");


Properties Pro = new properties ();


Pro.load (InputStream);





3. Reading parameters


Url=pro.getproperty ("url");


Password=pro.getproperty ("password");


User=pro.getproperty ("user");


Driverclass=pro.getproperty ("Driverclass");





Class.forName (Driverclass);


catch (Exception e) {


E.printstacktrace ();


SYSTEM.OUT.PRINTLN ("Registration failed!") "+ e.getmessage ());


throw new RuntimeException (e);


}


}





Get connection


public static Connection getconnection () {


Connection conn = null;


try {


Get connection


conn = drivermanager.getconnection (URL, user, password);


Get Statement Object


Statement Statement = Conn.createstatement ();


catch (Exception e) {


E.printstacktrace ();


}


Return conn;


}

Close Resource


public static void Close (Statement Statement, Connection Connection) {


{


try {


if (statement!= null)


Statement.close ();


if (connection!= null) {


Connection.close ();


}


catch (SQLException e) {


TODO auto-generated Catch block


E.printstacktrace ();


}


}


}


}

DQL operation

So how do you use JDBC to query data in a database?

Copy Code code as follows:
@Test


public void Testdsl () throws Exception {


Get connection


Cnn2=sqlutil.getconnection ();


Statement Statement = Cnn2.createstatement ();








Preparing SQL statements


String sql = "SELECT * from subject";





Call ExecuteQuery Execute Query statement


ResultSet res = statement.executequery (SQL);





Res points to the header at the end of the query, and to get the data must constantly point to the next line of the query's results, returning 0 when there is no next row of data.


while (Res.next ())


{


Gets the value of the field "Sjid" in the query result, and you want to specify the type


int id = res.getint ("Sjid");





Gets the value of the field "Sjname" in the query result, and you want to specify the type


String name = res.getstring ("Sjname");


SYSTEM.OUT.PRINTLN ("ID:" + ID + "Name:" + name);


}


Sqlutil.close (statement, CNN2);


}

The above is to use the statement object to manipulate the database ~

6. Using the PreparedStatement operation database

PreparedStatement object is actually a special statement object, it can precompile SQL statements, when you set the parameters, and then you can execute the SQL statement ~

DDL and DML operations

Copy Code code as follows:
Package com.vmaxtam.sqltest;

Import java.sql.Connection;
Import java.sql.PreparedStatement;

Import Org.junit.Test;

public class Preparedstatementtest {
Connection Connection = null;
@Test
public void Ddldmltest () throws Exception {
1. Get connection
Connection = Sqlutil.getconnection ();

2. Prepare SQL statements, precompiled statements, parameters used? Number occupies
String sql = "INSERT into SUBJECT VALUES (?,?)";

3. Access to Objects
PreparedStatement preparedstatement = connection.preparestatement (sql);

/*
* 4. Set the SQL parameter requires the number of parameters, and know its type the first sentence of the SQL statement is the int type, the parameter value is set to 3, and so on
*/
Preparedstatement.setint (1, 3);
Preparedstatement.setstring (2, "English");

5. Submit SQL to database execution
int num = Preparedstatement.executeupdate ();

System.out.println ("have" + num + "record affected");

Sqlutil.close (PreparedStatement, connection);
}
}

The above is the use of the PreparedStatement object to send the INSERT statement, the same, DDL and DML class statements can be sent according to this.

The benefits of PreparedStatement precompilation:

PreparedStatement precompilation allows you to query for different targets by setting different parameters, and at the database end, only one precompiled statement is saved, but if you use statement to send a statement, each one is sent and a database is saved. This can result in significant memory consumption.

DQL operation

Copy Code code as follows:
@Test


public void Dqltest () throws Exception {


1. Get connection


Connection = Sqlutil.getconnection ();

2. Prepare SQL statements, precompiled statements, parameters used? Number occupies
String sql = "SELECT * from subject where sjid=?" or sjname=? ";

3. Access to Objects
PreparedStatement preparedstatement = connection.preparestatement (sql);

       /*
         * 4. Set SQL parameters The required argument is the number one and knows its type the first sentence of the SQL statement is the int type, the parameter value is set to 3, and so on
         *
        preparedstatement.setint (1, 2);
        preparedstatement.setstring (2, "language");

5. Submit SQL to database execution
ResultSet rst = Preparedstatement.executequery ();

6. Iteration result set
while (Rst.next ())
{
int id = rst.getint ("Sjid");
String name = rst.getstring ("Sjname");
SYSTEM.OUT.PRINTLN ("ID:" + ID + "Name:" + name);
}

7. Close the connection
Sqlutil.close (PreparedStatement, connection);
}

It is also called executequery () method can be obtained after the result set iteration output ~

Since statement is so similar to PreparedStatement, compare their advantages and disadvantages.

The difference between Statement and PreparedStatement:

1. Different grammar

Statement only supports static compilation, and SQL statements are written to death.

PreparedStatement support precompilation, using? Number to occupy the position.

2. Different efficiency

statement sends an SQL statement each time, does not support caching, execution is inefficient.

PreparedStatement support precompilation, slow existence of the database, just send parameters, execution efficiency.

3. Different security

Statement are easily injected.

Injection: Cunning molecules can write special SQL statements to invade a database.

For example: To query a user's information

General: SELECT * from User_list where username=xxx and password=xxx; (xxx Here is supposed to fill in their username and password for the user)

Injection case: SELECT * from user_list where username= ' abc ' or 1=1-password=xxx;

This 1=1 identity, and adds a "--" number before the password, and the subsequent content becomes a comment that is not executed. In other words, this will enable you to query all user information without a password.

PreparedStatement, because the parameters in the SQL statement are specified, so the injection can be prevented.

Conclusion: It is recommended to use PreparedStatement because it is faster and more secure .

7. Execute stored procedures using CallableStatement

Using CallableStatement only executes stored procedures, creating stored procedures we still want to create in the database.

Step 1

Now the database builds a stored procedure:

Copy Code code as follows:
DELIMITER $
CREATE PROCEDURE Pro_add (in an INT, in B VARCHAR (M), out C INT)
BEGIN
SELECT * from SUBJECT WHERE sjid=a OR sjname=b;
SET C=a+a+a+a;
End $

Step 2

Execute with Java code and get output parameters

Copy Code code as follows:
@Test


public void Calast () throws Exception {


Get connection


Connection= sqlutil.getconnection ();


Preparing SQL statements


String sql = "Call Pro_add (?,?,?)";





Get CallableStatement Object


CallableStatement CBS = Connection.preparecall (SQL);





Set input parameters, just like PreparedStatement


Cbs.setint (1, 3);


Cbs.setstring (2, "mathematics");





/* So how do I set output parameters?


* need to register OUTPUT parameters!


*/


Cbs.registeroutparameter (3, Java.sql.Types.INTEGER);//need to use built-in objects to set parameter types





Execute SQL statement


Cbs.executequery ();





Using GetXXX method to get the output parameter of the corresponding position


Integer num= Cbs.getint (3);





System.out.println ("a*4 is" + num);





Close Resource


Sqlutil.close (CBS, Connection);


}

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.