有时候 使用框架,或许没有直接操作数据库来的快, 或者说是使用框架太麻烦,有个直接操作数据库的工具类多好,故直接上干货,写下如下代码: private static Logger logger = Logger.getLogger(DBHelper.class.getName()); /** * 纯 java 式的连接 定义常量
有时候
使用框架,或许没有直接操作数据库来的快,
或者说是使用框架太麻烦,有个直接操作数据库的工具类多好,故直接上干货,写下如下代码:
private static Logger logger = Logger.getLogger(DBHelper.class.getName());
/**
* 纯 java 式的连接 定义常量来存储配置
*/
public static String DRIVER = null;
public static String URL = null;
public static String USER = null;
public static String PASS = null;
Connection conn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
// 获得数据连接信息.
static {
Properties pops = new Properties();
InputStream inStream;
try {
inStream = DBCommandUtils.class.getResourceAsStream("/jdbc.properties");
pops.load(inStream);
} catch (FileNotFoundException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
}
URL = pops.getProperty("datasource.url");
USER = pops.getProperty("datasource.username");
PASS = pops.getProperty("datasource.password");
DRIVER = pops.getProperty("datasource.driverClassName");
}
/**
* 得到数据库连接
*/
public Connection getConn() {
try {
if (DRIVER == null || USER == null || PASS == null || URL == null) {
Properties pops = new Properties();
InputStream inStream;
try {
inStream = DBCommandUtils.class
.getResourceAsStream("/jdbc.properties");
pops.load(inStream);
} catch (FileNotFoundException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
}
URL = pops.getProperty("datasource.url");
USER = pops.getProperty("datasource.username");
PASS = pops.getProperty("datasource.password");
DRIVER = pops.getProperty("datasource.driverClassName");
}
// 获得链接.
Class.forName(DRIVER);
conn = (Connection) DriverManager.getConnection(URL, USER, PASS);
return conn;
} catch (Exception e) {
logger.error("获取链接失败!" + e.getLocalizedMessage());
return null;
}
}
/**
* 要执行的增 ,删 ,改 的操作,不执行查询 (注意参数的使用)
*/
public int executeSQL(String preparedSql, String[] param) {
int count = 0;
/**
* 执行的操作
*/
try {
if (conn == null) {
conn = getConn(); // 获得连接
}
pstmt = conn.prepareStatement(preparedSql);// 要执行的 sql 语句
if (param != null) {
for (int i = 0; i
pstmt.setString(1 + i, param[i]);// 为预编译sql设置参数
}
}
count = pstmt.executeUpdate(); // 执行 sql 语句
} catch (SQLException e) {
logger.error(e.getMessage()); // 处理SQLException异常
return -1;
}
return count; // 返回结果
}
/**
* 要执行的增 ,删 ,改 的操作,不执行查询 (注意参数的使用)
*/
public int executeSQL(String preparedSql) {
int count = 0;
/**
* 执行的操作
*/
try {
if (conn == null) {
conn = getConn(); // 获得连接
}
pstmt = conn.prepareStatement(preparedSql);// 要执行的 sql 语句
count = pstmt.executeUpdate(); // 执行 sql 语句
} catch (SQLException e) {
logger.error(e.getMessage()); // 处理SQLException异常
return -1;
}
return count; // 返回结果
}
/**
* 要执行的增 ,删 ,改 的操作,不执行查询 (注意参数的使用)
*/
public int[] executeSQLs(String[] sqls) {
int[] count = null;
/**
* 执行的操作
*/
try {
if (conn == null) {
conn = getConn(); // 获得连接
}
stmt = conn.createStatement();
for (String sql : sqls) {
stmt.addBatch(sql);
}
count = stmt.executeBatch(); // 执行 sql 语句
} catch (SQLException e) {
logger.error(e.getMessage()); // 处理SQLException异常
return null;
}
return count; // 返回结果
}
/**
* 要执行的复杂操作
*/
public boolean executeAllSQL(String preparedSql) {
boolean result = false;
try {
if (conn == null) {
conn = getConn(); // 获得连接
}
pstmt = conn.prepareStatement(preparedSql);// 要执行的 sql 语句
result = pstmt.execute();
} catch (SQLException e) {
logger.error(e.getMessage()); // 处理SQLException异常
}
return result; // 返回结果
}
/**
* 使用PreparedStatement查询数据
*
* @param sql
* @param params
* 参数列表
* @return 结果集 不要关闭连接
*/
public ResultSet selectSQL(String sql, String[] param) {
try {
if (conn == null) {
conn = getConn(); // 获得连接
}
pstmt = conn.prepareStatement(sql); // 执行sql语句
for (int i = 0; i
pstmt.setString(i + 1, param[i]);
}
rs = pstmt.executeQuery(); // 执行的结果
} catch (SQLException e1) {
logger.error(e1.getMessage());
}
return rs;
}
/**
* 使用statement执行查询
*
* @param sql
* 执行的SQL语句
* @return 不可关闭连接
*/
public ResultSet selectSQL(String sql) {
try {
if (conn == null) {
conn = getConn(); // 获得连接
}
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
} catch (SQLException e1) {
logger.error(e1.getMessage());
}
return rs;
}
/**
* 关闭所有的接口 (注意括号中的参数)
*/
public void closeAll() {
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception e) {
logger.error(e.getMessage());
}
}
// 判断是否关闭,要时没有关闭,就让它关闭,并给它附一空值(null),下同
if (pstmt != null) {
try {
pstmt.close();
pstmt = null;
} catch (SQLException e) {
logger.error(e.getMessage()); // 异常处理
}
}
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
logger.error(e.getMessage()); // 异常处理
}
}
if (conn != null) {
try {
conn.close();
conn = null;
} catch (SQLException e) {
logger.error(e.getMessage()); // 异常处理
}
}
}
/**
* 检查数据库连接
*
* @param manager
* @return true:无法连接;false:正常
*/
public boolean checkCon(DBCommandUtils manager) {
boolean result = false;
try {
result = getConn().isClosed();
} catch (SQLException e) {
logger.error(e.getMessage());
}
return result;
}
/**
* 编写测试类来进行对数据库的检验
*/
public static void main(String[] args) {
DBCommandUtils manager = new DBCommandUtils();
try {
System.out.println(manager.getConn().isClosed());
} catch (SQLException e) {
logger.error(e.getMessage()); // 抛出异常
}
}
这个玩意就可以直接拿来用了,其实还是很不错的玩意。。。
自然是没有使用关系型框架舒服了。
不过: 有了这个有时候不用框架也是比较舒服的。

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment