Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. package learn;
  2. import java.sql.*;
  3. import java.util.logging.Level;
  4. import java.util.logging.Logger;
  5. import javax.swing.JOptionPane;
  6.  
  7. public class mySqlConnect{
  8.  
  9. protected Connection con = null;
  10. protected Statement stm = null;
  11. protected PreparedStatement prstm = null;
  12. protected CallableStatement cstm = null;
  13. private final String url = "jdbc:sqlserver://localhost:1433;databaseName=ThuVien;user=sa;password=123456";
  14.  
  15. public boolean openConnection() throws SQLException{
  16. if(con.isClosed()){
  17. try{
  18. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  19. con = java.sql.DriverManager.getConnection(url);
  20. return true;
  21. }
  22. catch (ClassNotFoundException | SQLException e){
  23. JOptionPane.showMessageDialog(null,"Lỗi kết nối "+e);
  24. }
  25. }
  26. return false;
  27. }
  28.  
  29. public boolean closeConnection() throws SQLException{
  30. if(!con.isClosed()){
  31. con.close();
  32. return true;
  33. }
  34. return false;
  35. }
  36.  
  37. public boolean ExecuteNoneQuery (String sql) throws SQLException{
  38. if (openConnection()){
  39. try {
  40. stm = con.createStatement();
  41. stm.execute(sql);
  42. return true;
  43. } catch (SQLException ex) {
  44. Logger.getLogger(mySqlConnect.class.getName()).log(Level.SEVERE, null, ex);
  45. }finally {
  46. closeConnection();
  47. stm.close();
  48. }
  49. }
  50. return false;
  51. }
  52.  
  53. public ResultSet ExecuteTable(String sql) throws SQLException{
  54. if(openConnection()){
  55. try{
  56. stm = con.createStatement();
  57. ResultSet rs = stm.executeQuery(sql);
  58. return rs;
  59. }catch(Exception ex){
  60.  
  61. }finally{
  62. closeConnection();
  63. stm.close();
  64. }
  65. }
  66. return null;
  67. }
  68.  
  69. public static void main(String[] args) {
  70. mySqlConnect obj = new mySqlConnect();
  71. try {
  72. ResultSet rs = obj.ExecuteTable("SELECT maSach from tb_Sach");
  73. while(rs.next()){
  74. String tenSach = rs.getString("maSach");
  75. System.out.println("\n"+tenSach);
  76. }
  77. } catch (SQLException ex) {
  78. Logger.getLogger(mySqlConnect.class.getName()).log(Level.SEVERE, null, ex);
  79. }
  80.  
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement