Skip to content

Instantly share code, notes, and snippets.

@behitek
Created December 8, 2016 15:14
Show Gist options
  • Save behitek/fa19ea1a07515f68a7dfdff45a55d532 to your computer and use it in GitHub Desktop.
Save behitek/fa19ea1a07515f68a7dfdff45a55d532 to your computer and use it in GitHub Desktop.
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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment