Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package learn;
- import java.sql.*;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.swing.JOptionPane;
- public class mySqlConnect{
- protected Connection con = null;
- protected Statement stm = null;
- protected PreparedStatement prstm = null;
- protected CallableStatement cstm = null;
- private final String url = "jdbc:sqlserver://localhost:1433;databaseName=ThuVien;user=sa;password=123456";
- public boolean openConnection() throws SQLException{
- if(con.isClosed()){
- try{
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- con = java.sql.DriverManager.getConnection(url);
- return true;
- }
- catch (ClassNotFoundException | SQLException e){
- JOptionPane.showMessageDialog(null,"Lỗi kết nối "+e);
- }
- }
- return false;
- }
- public boolean closeConnection() throws SQLException{
- if(!con.isClosed()){
- con.close();
- return true;
- }
- return false;
- }
- public boolean ExecuteNoneQuery (String sql) throws SQLException{
- if (openConnection()){
- try {
- stm = con.createStatement();
- stm.execute(sql);
- return true;
- } catch (SQLException ex) {
- Logger.getLogger(mySqlConnect.class.getName()).log(Level.SEVERE, null, ex);
- }finally {
- closeConnection();
- stm.close();
- }
- }
- return false;
- }
- public ResultSet ExecuteTable(String sql) throws SQLException{
- if(openConnection()){
- try{
- stm = con.createStatement();
- ResultSet rs = stm.executeQuery(sql);
- return rs;
- }catch(Exception ex){
- }finally{
- closeConnection();
- stm.close();
- }
- }
- return null;
- }
- public static void main(String[] args) {
- mySqlConnect obj = new mySqlConnect();
- try {
- ResultSet rs = obj.ExecuteTable("SELECT maSach from tb_Sach");
- while(rs.next()){
- String tenSach = rs.getString("maSach");
- System.out.println("\n"+tenSach);
- }
- } catch (SQLException ex) {
- Logger.getLogger(mySqlConnect.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement