Java——MySQL数据库操作类
1 package pkg.src.database; 2 3 import java.sql.*; 4 5 public class MYSQL_DBManager { 6 7 // 8 //定义数据库相关的变量 9 static String Drivername="com.mysql.jdbc.Driver"; 10 static String IP="localhost"; 11 static String Port="3306"; 12 static String DataBaseName="world"; 13 static String UserName="root"; 14 static String Password="123456"; 15 16 17 //定义数据库操作需要的成员变量 18 private static Connection conn=null; 19 private static Statement stmt=null; 20 private static PreparedStatement prstmt=null; 21 private static ResultSet rst=null; 22 private ResultSetMetaData rsmt=null; 23 public String setIP(String sIP){ 24 IP=sIP; 25 return IP; 26 } 27 public String setUsername(String userName){ 28 UserName=userName; 29 return UserName; 30 } 31 public String setPassword(String passwordS){ 32 Password=passwordS; 33 return Password; 34 } 35 36 private static String URL="jdbc:mysql://"+IP+"/"+Port+"/"+DataBaseName+"?" 37 +"user="+UserName+"&"+"password="+Password+"&userUnicode=true&characterEncoding=UTF-8"; 38 39 40 41 42 43 public static void getConnection(){ 44 //连接到数据库 45 //加载驱动 46 try { 47 //动态加载jdbc驱动 48 Class.forName(Drivername); 49 //or: com.mysql.jdbc.Driver driver=new com.mysql.jdbc.Driver(); 50 //or: new com.mysql.jdbc.Driver(); 51 System.out.println("Load Driver success."); 52 //conn代表一个数据库链接 53 conn=DriverManager.getConnection(URL); 54 System.out.println("conn创建成功!"); 55 stmt=conn.createStatement(); 56 } catch (ClassNotFoundException e) { 57 // TODO Auto-generated catch block 58 e.printStackTrace(); 59 } catch (SQLException e) { 60 // TODO Auto-generated catch block 61 e.printStackTrace(); 62 } 63 } 64 //执行数据库的查询操作,返回查询得到的数据集rst 65 public static ResultSet executeQuery(String SQLCommand){ 66 try { 67 rst=stmt.executeQuery(SQLCommand); 68 } catch (SQLException e) { 69 // TODO Auto-generated catch block 70 e.printStackTrace(); 71 } 72 return rst; 73 } 74 //执行数据库的更新操作,包括删除操作和修改操作 75 public static void executeUpdate(String SQLCommand){ 76 try { 77 stmt.executeUpdate(SQLCommand); 78 } catch (SQLException e) { 79 // TODO Auto-generated catch block 80 e.printStackTrace(); 81 } 82 } 83 //数据库当前的连接状态是什么样 84 public void isConnected(){ 85 try { 86 if(conn.isClosed()){ 87 System.out.println("database connection is still openning."); 88 }else{ 89 System.out.println("database connection is closed."); 90 } 91 } catch (SQLException e) { 92 // TODO Auto-generated catch block 93 e.printStackTrace(); 94 } 95 } 96 //关闭数据库链接 97 private void ShutdonwConnection(){ 98 try { 99 conn.close(); 100 } catch (SQLException e) { 101 // TODO Auto-generated catch block 102 e.printStackTrace(); 103 } 104 try { 105 stmt.close(); 106 } catch (SQLException e) { 107 // TODO Auto-generated catch block 108 e.printStackTrace(); 109 } 110 try { 111 prstmt.close(); 112 } catch (SQLException e) { 113 // TODO Auto-generated catch block 114 e.printStackTrace(); 115 } 116 rst=null; 117 rsmt=null; 118 } 119 //把数据库查询结果加载到JTable中 120 public javax.swing.JTable loadRstToJTable(){ 121 } 122 }