Jump to content
razvandragos29

Apelare Clasa Baza de date

Recommended Posts

Posted

Am realizat o conexiune cu baza de date dar vreau daca e posibil sa pot apela conexiunea aia in alte clase ceva de genu new Database(); si asta sa imi aduca tot codul scris in Database pentru a nu scrie de fiecare data asta e codul meu pentru conexiunea cu baza de date

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Database {
public static void main(String[] args) {
try {


// Note :
// • SQL Server's port no can be found by using TCPView s/w
// OR
// • You can also set a fixed port for the server in Sql server TCP/IP
// properties
// • Sql Server's TCP/IP should be enabled first for this
// • A 'SQL' user should be created and GRANTED access to the Database
// • Rest is just as normal JDBC

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("# - Driver Loaded");


String server = " ";
int port = 1433;
String user = ""; // Sql server username
String password = ";
String database = "";

String jdbcUrl = "jdbc:sqlserver://"+server+":"+port+";user="+user+";password="+password+";databaseName="+database+"";

Connection con = DriverManager.getConnection(jdbcUrl);
System.out.println("# - Connection Obtained");

Statement stmt = con.createStatement();
System.out.println("# - Statement Created");

ResultSet rs = stmt.executeQuery("SELECT * FROM PERSON;");
System.out.println("# - Query Executed");

if(rs.next()) {
System.out.println("Product Count : "+rs.getString(1));
}

rs.close();
stmt.close();
con.close();
System.out.println("# - Resources released");
} catch (Exception ex) {
System.out.println("Error : "+ex);
}
}
}

si asta e clasa mea de Log in

 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class GUILOGIN extends JFrame {
//componente

JTextField user;
JPasswordField pass;
JButton login;
JLabel username;
JLabel password;

//final componente

public GUILOGIN() {

super("Log in Window");
setSize(300,200);
setLayout(null);
Componente();
populare();
add(user);
add(pass);
add(login);
add(username);
add(password);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void Componente() {




user=new JTextField(15);
user.setBounds(70, 30, 150, 20);

pass=new JPasswordField(15);
pass.setBounds(70, 65, 150, 20);

login=new JButton("Log in");
login.setBounds(110,100,80,20);
login.addActionListener(actiune);
username=new JLabel("Username");
username.setBounds(1,30,70,20);

password=new JLabel("Password");
password.setBounds(1, 65, 70, 20);
}

public void populare() {
Vector<Employe> lista = new Vector<Employe>();
Employe dragos=new User(1,"Dragos","12345","Razvan","razvan","normal",0f,0f, 0f, "Comentarii","bonusuri","Penatyss");
Employe george=new Admin(2,"George","344556","George","12345","avansat","Administrator");
lista.add(dragos);
lista.add(george);
}

Actiune actiune=new Actiune();
public class Actiune implements ActionListener {

@Override
public void actionPerformed(ActionEvent argument) {
populare();
Vector<Employe> lista = new Vector<Employe>();
Employe dragos=new User(1,"Dragos","12345","Razvan","razvan","normal",0f,0f, 0f, "Comentarii","bonusuri","Penatyss");
Employe george=new Admin(2,"George","344556","George","12345","avansat","Administrator");
lista.add(dragos);
lista.add(george);
String pname=user.getText();
String ppass=new String(pass.getPassword());

if(argument.getSource()==login) {

for(Employe employes: lista){
if(employes.autentificare(pname, ppass)) {
if(employes.permisiuni()==false) {
System.out.println("Userul este normal");
dispose();
break; }
else if(employes.permisiuni()==true) {
System.out.println("Userul este admin");
dispose();
break; }
}
else {
System.out.println("Eroare");
}


}

}

}
}
}//clasa Final

eu vreau sa extrang useri din baza de date si in functie de tip sa apara ceva ..si apoi sa apelez intr-o clasa numita main si sa ruleze

Posted

Din cate stiu, chestiile valabile in c++ sunt in mare valabile si in java.

Creaza un membru de tipul Database in Guilogon, si fie pasezi in constructor Database-ul pe care tu l-ai creat, fie crezi o functie separata care sa faca asta.

daca doresti sa folosesti o functie separata aceasta presupun ca ar trebui sa arate ceva degenul


public void SeteazaDatabase(Database db)
{
m_db = db; // m_db fiind membrul din clasa GUILOGIN
}

Posted

nu, faci un mebru doar Database m_db;

astuia ii atribui in constructor sau prin o functie separata valoarea primei Database pe care ai initializat-o tu unde ai initializat-o.

Posted

Ai inceput cu chestii unpic mai avansate si nu stapanesti chestiile de baza din OOP si Java. Asta nu e prea bine dar o sa te indrept putin spre directia buna.

In primul rand trebuie sa scoti mainul din clasa Database si sa faci o clasa separata care sa contina functia main. Aceea va fi punctul de unde programul incepe.

Deci sa zicem ca faci o clasa Launcher care arata cam asa:

public class Launcher {

public static void main(String[] args) {

new GUILOGIN();

}

}

In functia Main creezi un obiect de tipul GUILOGIN. Asta am facut mai sus cu new GUILOGIN();

Atentie la numele de clase, nu mai da numele claselor cu litere mari. Numele unei clasa incepe cu litera mare iar restul literelor mici sau daca ai combinatii de cuvinte in genul ConexiuneLaBazaDeDate tot timpul prima litera a cuvantului sa fie litera mare.

Asta asa ca o paranteza la coding style.

Asta iti va crea si afisa fereastra ta.

Presupun ca vrei sa lucrezi cu baza de date prin intermediul interfetei grafice asa ca deocamdata lasam clasa Launcher asa cum este acum.

Acum modificam clasa Database si in primul rand stergem de acolo functia main si construim un constructor.

In acel constructor setam chestiile statice necesare pentru a crea o conexiune si facem stringul jdbcURL un field al clasei database pentru a putea fi accesat intern in clasa Database si de catre alte metode.

Dupa asta facem o metoda queryUserType care returneaza true pentru admin si false pentru un user normal. Am facut asa pentru ca ai facut ceva asemanator in in clasa ta de GUI dar asta e o modalitate proasta pentru a verifica daca un user este admin sau nu. O sa iti dai si singur seama de ce. Am presupus ca ai in baza de date un string cu username, un string cu pass si o valoare booleana care reprezinta tipul de utilizator. Posibil sa nu ai asa dar din moment ce nu ai precizat iti da asa un exemplu ca sa intelegi cum functioneaza. O sa adaptezi tu codul la nevoile tale. Acu nici chiar mura in gura. :)

Clasa ta Database o sa arate ceva de genul in urma schimbarilor.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

public class Database {

private String jdbcUrl;

public Database()

{

try {

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

System.out.println("# - Driver Loaded");

String server = " ";

int port = 1433;

String user = ""; // Sql server username

String password = "";

String database = "";

jdbcUrl = "jdbc:sqlserver://"+server+":"+port+";user="+user+";password="+password+";databaseName="+database+"";

}

public boolean queryUserType(String username, String password){

try {

Connection con = DriverManager.getConnection(jdbcUrl);

System.out.println("# - Connection Obtained");

Statement stmt = con.createStatement();

System.out.println("# - Statement Created");

ResultSet rs = stmt.executeQuery("SELECT admin FROM PERSON WHERE " +

"username='" + username + "'" +

"AND password='" + password + "';");

System.out.println("# - Query Executed");

while(rs.next()) {

boolean userType = rs.getBoolean("admin");

return userType;

}

rs.close();

stmt.close();

con.close();

System.out.println("# - Resources released");

} catch (Exception ex) {

System.out.println("Error : "+ex);

}

return false;

}

}

Acum tot ce trebuie sa faci in clasa De GUI. (Din nou, aici ar trebui sa ai alta clasa care sa contina logica de validare si control iar in clasa de GUI sa ai doar partea de GUI si nimic altceva, nici un alt cod care sa faca altceva decat construirea GUI.

Pentru simplitate iti dau exemplu asa cum ai inceput tu.

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.ArrayList;

import java.util.Vector;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPasswordField;

import javax.swing.JTextField;

public class GUILOGIN extends JFrame {

//componente

JTextField user;

JPasswordField pass;

JButton login;

JLabel username;

JLabel password;

//final componente

public GUILOGIN() {

super("Log in Window");

setSize(300,200);

setLayout(null);

Componente();

populare();

add(user);

add(pass);

add(login);

add(username);

add(password);

setResizable(false);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public void Componente() {

user=new JTextField(15);

user.setBounds(70, 30, 150, 20);

pass=new JPasswordField(15);

pass.setBounds(70, 65, 150, 20);

login=new JButton("Log in");

login.setBounds(110,100,80,20);

login.addActionListener(actiune);

username=new JLabel("Username");

username.setBounds(1,30,70,20);

password=new JLabel("Password");

password.setBounds(1, 65, 70, 20);

}

public void populare() {

Vector<Employe> lista = new Vector<Employe>();

Employe dragos=new User(1,"Dragos","12345","Razvan","razvan","normal",0f,0f, 0f, "Comentarii","bonusuri","Penatyss");

Employe george=new Admin(2,"George","344556","George","12345","avansat","Administrator");

lista.add(dragos);

lista.add(george);

}

Actiune actiune=new Actiune();

public class Actiune implements ActionListener {

@Override

public void actionPerformed(ActionEvent argument) {

populare();

Vector<Employe> lista = new Vector<Employe>();

Employe dragos=new User(1,"Dragos","12345","Razvan","razvan","normal",0f,0f, 0f, "Comentarii","bonusuri","Penatyss");

Employe george=new Admin(2,"George","344556","George","12345","avansat","Administrator");

lista.add(dragos);

lista.add(george);

String pname=user.getText();

String ppass=new String(pass.getPassword());

if(argument.getSource()==login) {

Database dbHandler = new Database();

boolean admin = dbHandler.queryUserType(pname, ppass);

if (admin){

System.out.println("Userul este admin");

}else{

System.out.println("Userul este normal");

}

/* for(Employe employes: lista){

if(employes.autentificare(pname, ppass)) {

if(employes.permisiuni()==false) {

System.out.println("Userul este normal");

dispose();

break; }

else if(employes.permisiuni()==true) {

System.out.println("Userul este admin");

dispose();

break; }

}

else {

System.out.println("Eroare");

}*/

}

}

}

}

}//clasa Final

In momentul in care vrei sa verifici tipul unui user pur si simplu instantiezi calsa Database dupa care apelezi metoda queryUserType care executa query-ul catre baza de date si returneaza un boolean pe care il stochez in variabila admin si apoi verifica daca admin e true sau false si printez mesajul.

Atentie, metoda aceea de verificare returneaza false (adica user normal) chiar daca tu introduci un nume de utilizator si o parola care nu exista in db. De asta ziceam ca nu e prea ok sa verifici tipul de user cu true si false. Sau poti sa implementezi altfel functia dar la astea te mai gandesti tu.

Spor!

Posted

Iti multumesc din inima , aveam deja clasa Launcher facuta numai ca la mine se numeste main ..am incercat si eu sa scot mainu unde aveam conexiunea catre baza de date insa imi dadea o eroare , incercasem sa fac un constructor dar tot eroare probabil facem eu ceva gresit acuma imi da o eroare destul de mare

 java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLSer  verDriver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at jar_pm.Database.<init>(Database.java:14)
at jar_pm.GUILOGIN$Actiune.actionPerformed(GUILOGIN.java:80)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

nu am mai lucrat cu baze de date si cu java de asta imi este greu cu java am mai lucrat si am facut vreo 2-3 proiecte mici dar am ceva in spate :D

Posted

greseala de la copy-paste

com.microsoft.sqlserver.jdbc.SQLSer verDriver

sunt 2 spatii acolo. E gresit numele pentru driver. Cum aveai tu in primul post cred ca e ok.

Posted

Da, asa am presupus ca ai in baza de date. Poate ai altfel, nu stiu.

Poti sa adaptezi codul si query-ul SQL in functie de necesitati, nu trebuie sa copiezi tot ce am scris. Am facut asa ca si un exemplu sa intelegi cam cum ar functiona si cum ti-ai rezolva problema.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...