Java类——JDBC链接、并操作MySQL数据库

时间:2022-08-07 06:27:20

Java——MySQL数据库操作类

 package pkg.src.database;

 import java.sql.*;

 public class MYSQL_DBManager {

     //
//定义数据库相关的变量
static String Drivername="com.mysql.jdbc.Driver";
static String IP="localhost";
static String Port="3306";
static String DataBaseName="world";
static String UserName="root";
static String Password="123456"; //定义数据库操作需要的成员变量
private static Connection conn=null;
private static Statement stmt=null;
private static PreparedStatement prstmt=null;
private static ResultSet rst=null;
private ResultSetMetaData rsmt=null;
public String setIP(String sIP){
IP=sIP;
return IP;
}
public String setUsername(String userName){
UserName=userName;
return UserName;
}
public String setPassword(String passwordS){
Password=passwordS;
return Password;
} private static String URL="jdbc:mysql://"+IP+"/"+Port+"/"+DataBaseName+"?"
+"user="+UserName+"&"+"password="+Password+"&userUnicode=true&characterEncoding=UTF-8"; public static void getConnection(){
//连接到数据库
//加载驱动
try {
//动态加载jdbc驱动
Class.forName(Drivername);
//or: com.mysql.jdbc.Driver driver=new com.mysql.jdbc.Driver();
//or: new com.mysql.jdbc.Driver();
System.out.println("Load Driver success.");
//conn代表一个数据库链接
conn=DriverManager.getConnection(URL);
System.out.println("conn创建成功!");
stmt=conn.createStatement();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//执行数据库的查询操作,返回查询得到的数据集rst
public static ResultSet executeQuery(String SQLCommand){
try {
rst=stmt.executeQuery(SQLCommand);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rst;
}
//执行数据库的更新操作,包括删除操作和修改操作
public static void executeUpdate(String SQLCommand){
try {
stmt.executeUpdate(SQLCommand);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//数据库当前的连接状态是什么样
public void isConnected(){
try {
if(conn.isClosed()){
System.out.println("database connection is still openning.");
}else{
System.out.println("database connection is closed.");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//关闭数据库链接
private void ShutdonwConnection(){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
prstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rst=null;
rsmt=null;
}
//把数据库查询结果加载到JTable中
public javax.swing.JTable loadRstToJTable(){
}
}