📄 conndb.java
字号:
package com.dao.conn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnDB {
public ConnDB() {
}
// 如何从配置文件里读出来的信息
private static Connection conn = null;
private static String driverName = "com.mysql.jdbc.Driver"; // JDBC驱动
private static String userName = "root"; // 数据库登录用户名
private static String password = "lxj504241"; // 数据库登录密码(如果没有设置,可以为空)
private static String dbName = "officesystem"; // 数据库名称
private Statement stmt; // 数据库管理员
private ResultSet res; // 返回结果集
private static String url = "jdbc:mysql://localhost:3306/" + dbName
+ "?user=" + userName + "&password=" + password;
public static Connection getConnection() {
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public ResultSet executeQuery(String sql) {
// 对数据库进行查询操作
try {
conn = this.getConnection();
stmt = conn.createStatement();
try {
res = stmt.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return res;
}
public int update(String sql) {
// 对数据库信息进行更新操作
int count = 0;
try {
if (conn == null) {
getConnection();
}
stmt = conn.createStatement();
count = stmt.executeUpdate(sql);
return count;
} catch (SQLException e) {
e.printStackTrace();
return 0;
} finally {
this.close();
}
}
public void close() {
// 关闭数据库连接
if (res != null) {
try {
res.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
res = null;
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
stmt = null;
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
conn = null;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -