JDBC 操作数据库
有时候 使用框架,或许没有直接操作数据库来的快, 或者说是使用框架太麻烦,有个直接操作数据库的工具类多好,故直接上干货,写下如下代码: 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()); // 抛出异常
}
}
这个玩意就可以直接拿来用了,其实还是很不错的玩意。。。
自然是没有使用关系型框架舒服了。
不过: 有了这个有时候不用框架也是比较舒服的。

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

BitgetLaunchpool is a dynamic platform designed for all cryptocurrency enthusiasts. BitgetLaunchpool stands out with its unique offering. Here, you can stake your tokens to unlock more rewards, including airdrops, high returns, and a generous prize pool exclusive to early participants. What is BitgetLaunchpool? BitgetLaunchpool is a cryptocurrency platform where tokens can be staked and earned with user-friendly terms and conditions. By investing BGB or other tokens in Launchpool, users have the opportunity to receive free airdrops, earnings and participate in generous bonus pools. The income from pledged assets is calculated within T+1 hours, and the rewards are based on

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.
