Home  >  Article  >  Database  >  Detailed explanation of JDBC connection to MySQL instance_MySQL

Detailed explanation of JDBC connection to MySQL instance_MySQL

WBOY
WBOYOriginal
2016-11-30 23:59:411021browse

JDBC connects to MySQL

JDBC connects to MySQL

Load and register JDBC driver

Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();

JDBC URL defines the connection between driver and data source

Standard syntax:

d10d500e8bec722476599c70ebc64c7f:2f760b855a77c9af4717b4b4aa44aebc:d7443e16a772550631d9755738121cfd

MySQL JDBC URL format:

jdbc:mysql//[hostname][:port]/[dbname][?param1=value1][¶m2=value2]….

Example: jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password

Common parameters:
user Username
password                                                           autoReconnect Connection failed, whether to reconnect (true/false)
maxReconnect The number of attempts to reconnect
initialTimeout The interval between trying to reconnect
maxRows Returns the maximum number of rows
useUnicode Whether to use Unicode font encoding (true/false)
characterEncoding What encoding (GB2312/UTF-8/…)
relaxAutocommit Whether to submit automatically (true/false)
capitalizeTypeNames The names of data definitions are expressed in uppercase letters

Create connection object


String url="jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password"; Connection con = DriverManager.getConnection(url);

Create SQL Statement Object


Statement stmt = con.createStatement();

Execute SQL statements


executeQuery()
String query = "select * from test";
ResultSet rs=stmt.executeQuery(query);
结果集ResultSet
while(rs.next())
{rs.getString(1);rs.getInt(2);}
executeUpdate()
String upd="insert into test (id,name) values(1001,xuzhaori)";
int con=stmt.executeUpdate(upd);
execute()

Example:


try
{
 }
catch(SQLException sqle)
{
}
finally
{
}

Java Types and SQL Types Technical Manual P421


PreparedStatement

PreparedStatement stmt = conn.prepareStatement("insert into test(id,name)values(?,?)");

stmt.setInt(1,id);
stmt.setString(2,name);

Note: Once the parameter value of a statement is set, the modified statement can be executed multiple times until it is cleared by calling the clearParameters() method


CallableStatement (pre-stored program) technical manual P430


JDBC2.0 use


The cursor in the ResultSet object moves freely up and down

Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs=stmt.executeQuery("select * from test");

public Statement createStatement(int resultSetType,int resultSetConcuttency) throws SQLException


resultSetType

TYPE_FORWARD_ONLY Only the next() method can be used.

TYPE_SCROLL_SENSITIVE can be moved up and down and the changed value can be obtained.
TYPE_SCROLL_INSENSITIVE can move up and down.

resultSetConcuttency


CONCUR_READ_ONLY Read only

CONCUR_UPDATABLE The ResultSet object can perform database additions, modifications, and removals

Directly use the ResultSet object to update data


New data

Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_PUDATABLE);
ResultSet uprs=stmt.executeQuery("select * from test");
uprs.moveToInsertRow();
uprs.updateInt(1,1001);
uprs.updateString(2,"许召日");
uprs.insertRow;

Update data

Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_PUDATABLE);
ResultSet uprs=stmt.executeQuery("select * from test");
uprs.last();
uprs.updateString("name","xuzhaori");
uprs.updateRow;

Delete data

Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_PUDATABLE);
ResultSet uprs=stmt.executeQuery("select * from test");
uprs.absolute(4);
uprs.deleteRow();

Batch processing

con.setAutoCommit(false); 关闭自动认可模式
Statement stmt=con.createStatement();
int[] rows;
stmt.addBatch("insert into test values(1001,xuzhaori)");
stmt.addBatch("insert into test values(1002,xuyalin)");
rows=stmt.executeBatch();
con.commit(); 没有任何错误,执行批处理stmt.executeBatch();

JNDI-Data Source and Connection Pool


Tomcat’s JDBC data source settings technical manual P439


Connection Pooling Tool-Proxool Var 0.8.3 Technical Manual P446


Set web.xml


<&#63;xml version="1.0" encoding="ISO-8859-1"&#63;>
<!--<&#63;xml version="1.0" encoding="GB2312"&#63;>-->
 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
….
<servlet>
<servlet-name>ServletConfigurator</servlet-name>
<servlet-class>org.logicalcobwebs.proxool.configuration.ServletConfigurator</servlet-class>
 
<init-param>
<param-name>propertyFile</param-name>
<param-value>WEB-INF/classes/Proxool.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
后端统计端口添加下列
<servlet>
<servlet-name>Admin</servlet-name>
<servlet-class>org.logicalcobwebs.proxool.admin.servlet.AdminServlet</servlet-class>
</servlet>
 
<servlet-mapping>
<servlet-name>Admin</servlet-name>
<url-pattern>/Admin</url-pattern>
</servlet-mapping>
 
….
 
</web-app>

Configure Proxool.properties


jdbc-0.proxool.alias=JSPBook
jdbc-0.proxool.driver-class=com.mysql.jdbc.Driver
jdbc-0.proxool.driver-url=jdbc:mysql://localhost:3306/sample_db&#63;user=root&password=browser&useUnicode=true&characterEncoding=UTF-8
jdbc-0.proxool.maximum-connection-count=10
jdbc-0.proxool.prototype-count=4
jdbc-0.proxool.house-keeping-test-sql=select CURRENT_DATE
jdbc-0.proxool.verbose=true
jdbc-0.proxool.statistics=10s,1m,1d  后端统计接口添加此行
jdbc-0.proxool.statistics-log-level=DEBUG


Use Proxool connection pool


Connection con = DriverManager.getConnection("proxool.JSPBook");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String query = "SELECT * FROM employee";
ResultSet rs = stmt.executeQuery(query);


Thanks for reading this article, I hope it can help everyone, thank you for your support of this site!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn