jdbc basic learning one

JDBC Basics

1. JDBC: Java DataBase Connectivity ( standard for connecting to databases in Java, developed by SUN ))

What is the relationship between JDBC and database drivers? JDBC is the specification, the abstraction layer, and the database driver is the concrete implementation.

The JDBC specification consists of some abstract classes and interfaces , which are generally placed in the java.sql.* or javax.sql.* packages ( with JDK )

2. JDBC coding steps: add the database driver to the build path

a) Load the driver and register the driver.

b) Obtain a connection to the database.

c)  Get the object representing the SQL statement and send the SQL to the database.

d) If there is a query result, get the object that encapsulates the query result.

e) traverse the result

f) Release occupied resources

3. Detailed explanation of commonly used JDBC interfaces and classes

a) DriverManager: Register the driver and get the connection to the database. Two driver registration methods:

The first: Register the driver: DriverManager.registDriver(new com.mysql.jdbc.Driver) ( not recommended )

Reasons: 1. Heavy reliance on specific database drivers

  2. It will cause the driver to register twice .

Second: use Class.forname("com.mysql.jdbc.DriverManger");

b) Connection: All interactions with the database must be based on a connection. Three commonly used connection methods:

1) static Connection getConnection(String url,String user,String password):

uri : the connection string to the database

MySQL connection string: mysql : jdbc:mysql://localhost:3306/day14 database name or jdbc:mysql:///day14 ( connect to the mysql database on the local default port )

user : the username of the database

password: the password of the database

2) static Connection getConnection(String url, Properties info) : Use the settings of Properties to connect the user name and password, the user name is user, and the password is: password

3) static Connection getConnection(String url): in the form of web page request. Add ?user=xxxx&password=xxxx; to the database connection string

c) Statement: The object representing this SQL statement. The commonly used methods are as follows:

1) ResultSet executeQuery(String sql): sql is a DQL statement, a query statement

2) int executeUpdate(String sql): sql is a DML statement. Or DDL that doesn't return results is fine . The return value represents the number of rows affected by the statement.

3) boolean execute(String sql): sql can be any sql statement. Returns true if a result set is returned . Otherwise return false .

d) ResultSet: represents the object returned by the query statement, which contains a collection of query results. Common methods are as follows:

1) boolean next(): move down a line

2) boolean previous(): move up one line

3) void absolute(int row): The record of the first row is 1 , specifying the number of rows to move

4) void beforeFirst(): move to the front of the first line

5) void afterLast(): move to the back of the last line

4. SQL injection: It is the behavior that users use some systems to not fully check the input data, so as to carry out malicious damage. It can also be accessed directly if the verification password is entered incorrectly.

5. PreparedStatement: try to use it instead of Statement

effect:

a)  Precompiled SQL statements, database execution efficiency is high

b)  prevent SQL injection

c) Support parameter placeholder "?" . That is, the parameters in the statement are replaced by ?, and then the method is used to assign each ? .

6.  Batch processing: When you need to send a batch of SQL statements to the database for execution, you should avoid sending and executing one by one from the database. Instead, JDBC batch processing should be used to improve execution efficiency. two ways

a)  When executing different statements, use Statement . code show as below:

public void test1() {

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

try {

conn = JdbcUtil.getConnection();

stmt = conn.createStatement();

String sql1 = "insert into t3 (id,content) values (1,'aaa1')";

String sql2 = "insert into t3 (id,content) values (2,'aaa2')";

String sql3 = "delete from t3 where id=1";

stmt.addBatch(sql1);

stmt.addBatch(sql2);

stmt.addBatch(sql3);

// Number of rows affected

int[] ii = stmt.executeBatch();

for (int i : ii) {

System.out.println(i);

}

 

} catch (Exception e) {

e.printStackTrace ();

} finally {

JdbcUtil.releses(rs, stmt, conn);

}

 

}

b) 当执行相同语句时,可以使用PreparedStatment

public void test2() {

Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;

try {

conn = JdbcUtil.getConnection();

for (int i = 0; i < 100; i++) {

stmt = conn

.prepareStatement("insert into customer values (?,?,?,?,?,?,?,?,?)");

stmt.setString(1, UUID.randomUUID().toString());

stmt.setString(2, "name" + i);

stmt.setString(3, i % 2 == 0 ? "0" : "1");

stmt.setString(4, "1990-10-29");

stmt.setString(5, "12345" + i);

stmt.setString(6, i + "[email protected]");

stmt.setString(7, i % 2 == 0 ? "饮茶" : "看电影");

stmt.setString(8, i % 2 == 0 ? "VIP" : "普通用户");

stmt.setString(9, "连连看" + i);

stmt.addBatch();

stmt.executeUpdate();

}

} catch (Exception e) {

e.printStackTrace();

} finally {

JdbcUtil.releses(rs, stmt, conn);

}

}

7. 大文本(Clob)数据存取

a) 将本地大数据文本设置到数据库中。

String path = classLoader();

File f = new File(path);

PreparedStatement.setCharacterStream(index, reader, length);

//注意length长度须设置,并且设置为int,利用File获取String path = classLoader();

String path = classLoader();

b) 将数据库中的大文本读取到硬盘

reader = resultSet. getCharacterStream(i);

reader = resultSet.getClob(i).getCharacterStream();

string s = resultSet.getString(i);

8. 大二进制数据(Blob)的存取

a) 将本地的二进制资源数据存储到数据库中

PreparedStatement. setBinaryStream(i, inputStream, length);

b) 将数据库中的二进制资源数据读取到硬盘

InputStream in  = resultSet.getBinaryStream(i);

InputStream in  = resultSet.getBlob(i).getBinaryStream();

9. 获取数据库自动生成的主键,使用PreparedStatement的getGeneratedKeys()方法

10. 调用存储过程。对于数据库中的存储过程,我们在程序中如何调用。

例如:存储过程是:

delimiter $$

 

 CREATE PROCEDURE spDemo2(IN inputParam VARCHAR(255), INOUT inOutParam

 varchar(255))

 BEGIN SELECT CONCAT('welcome---', inputParam) into

  inOutParam; END $$

 

 delimiter ;

 

调用过程是:

Connection conn = null;

CallableStatement stmt = null;

ResultSet rs = null;

try {

conn = JdbcUtil.getConnection();

stmt = conn.prepareCall("{call demoSp(?,?)}");

stmt.setString(1, "上海");

stmt.registerOutParameter(2, Types.VARCHAR);

stmt.execute();

String value = stmt.getString(2);

System.out.println(value);

} catch (Exception e) {

 

e.printStackTrace();

 

} finally {

JdbcUtil.releses(rs, stmt, conn);

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325482634&siteId=291194637