Java MySQL and JFrame connection "Cannot convert from boolean to connection" - java

public class BancoDeDados {
static String url = "jdbc:mysql://localhost:3306/Estoque";
static String pass = "admin";
static String user = "admin";
static Connection conexao = null;
public static boolean conecta() throws ClassNotFoundException {
try {
Class.forName("mysql.Driver");
conexao = DriverManager.getConnection(url, user, pass);
//System.out.println("Conectado.");
JOptionPane.showMessageDialog(null, "Conectado com Sucesso!");
return true;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Usuário e/ou senha estão incorretos!");
//System.out.println("Usuário e/ou senha estão errados.");
return false;
}
}
public class TelaPrincipal extends JFrame {
Connection conexao = null;
PreparedStatement pst = null;
ResultSet rs = null;
private JPanel contentPane;
private JTextField textLogin;
private JPasswordField textSenha;
public void logar(){
String sql = "Select *from Login WHERE Usuario = ? and senha = ?";
try{
pst = conexao.prepareStatement(sql);
pst.setString(1, textLogin.getText());
pst.setString(2, textSenha.getText());
rs = pst.executeQuery();
if(rs.next()){
TelaOpcoes telaopcoes = new TelaOpcoes();
telaopcoes.setVisible(true);
dispose();
}
else{
JOptionPane.showMessageDialog(null, "Usuário e Senha Inválidos");
}
}
catch(SQLException error){
JOptionPane.showMessageDialog(null, error);
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TelaPrincipal frame = new TelaPrincipal();
frame.setVisible(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TelaPrincipal() throws ClassNotFoundException {
conexao = BancoDeDados.conecta();
this.setLocationRelativeTo(null);
Its doing error on penultimate line " CONEXAO = BANCODEDADOS.CONECTA(); " saying that "Type mismatch : cannot convert from boolean to Connection"
Can somebody help me please? thanks!

CONEXAO = BANCODEDADOS.CONECTA();
Here CONEXAO is a connection variable
but the method
BANCODEDADOS.CONECTA(); returns a boolean value.
so change the type of variable CONEXAO
or create a new variable boolean type for store the result
Boolean conexao = BancoDeDados.conecta();

Your method returns a boolean (not a Connection). Change
public static boolean conecta() throws ClassNotFoundException {
try {
Class.forName("mysql.Driver");
conexao = DriverManager.getConnection(url, user, pass);
//System.out.println("Conectado.");
JOptionPane.showMessageDialog(null, "Conectado com Sucesso!");
return true;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Usuário e/ou senha estão incorretos!");
//System.out.println("Usuário e/ou senha estão errados.");
return false;
}
}
to something like
public static Connection conecta() {
Connection conn = null;
try {
Class.forName("mysql.Driver");
conn = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}

You are returning boolean from method conecta() and in constructor you are storing it to java.sql.Connection...
So change the return type of conecta() method to java.sql.Connection..

conexao is object of Connection and you are assigning value of method call BancoDeDados.conecta();[Which return boolean] to Connection.
Change your code like
Boolean result = BancoDeDados.conecta();
Or return conexao from method conecta to support your code.
Edit:
Driver to connect MySQL is com.mysql.jdbc.Driver. Change your code
Class.forName("mysql.Driver");
to
Class.forName("com.mysql.jdbc.Driver");

Related

How can I do a Login Form using three layer architecture and SQL server?

I have to do a Login form with Java, using three layer architecture and a database, I'm using SQL Server.
In my DA class I have this code: Basically what I'm trying to do is to send the jText user and jText password to the setPassword and setUser from the BL class.
u.setLogin(jtxtUsuario.getText());
u.setContrasenia(jtxtPassword.getText());
DA.DB.getConexion();
if (DA.DB.getStatus()) {
new jfrmInterno().setVisible(true);
}else {
JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no coincide con ninguna cuenta","",JOptionPane.ERROR_MESSAGE);
jtxtUsuario.setText("");
jtxtPassword.setText("");
}
In my BL class I have this code: In the method "validarUsuario" im sending the user and pass to the "setUsuario" method in the DA class.
public void setLogin(String login) {
if(login != null && login.length() > 3) {
_login = login;
}else {
_login = "Usuario Incorrecto";
}
}
public String getLogin() {
return _login;
}
public void setContrasenia(String contrasenia) {
if(contrasenia != null && contrasenia.length() > 6) {
_contrasenia = contrasenia;
}else {
_contrasenia = "Contraseña Incorrecta";
}
}
public String getContrasenia() {
return _contrasenia;
}
public void validarUsuario() {
admin.setUsuario(getLogin(), getContrasenia());
}
public Colegio() {
this("","");
}
public Colegio(String login, String contrasenia) {
setLogin(login);
setContrasenia(contrasenia);
}
}
The problem I have is in the DA class, I dont know how I can use the jText user and password and validate it against the user and password I have in the DB from the DA class. I create a method in the DA class called "setUsuario" which receives the user and password from the jText, but after that I dont know what else I can do, the idea is if the user and password are correct it should open a new Jframe.
public static Connection getConexion() {
status = false;
String url = "jdbc:sqlserver://localhost:1433;databaseName=Colegio";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}catch (ClassNotFoundException e) {
System.out.println("No se pudo establecer conexión");
}
try {
cn = DriverManager.getConnection(url);
PreparedStatement ps = cn.prepareStatement("SELECT * FROM [dbo].[Login] where NombreUsuario=? AND Contrasenia=?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
status = true;
}catch (SQLException e) {
}
return cn;
}
public void setUsuario(String user, String pass) {
DB.user = user;
DB.pass = pass;
}
In your DA class, you have to check if there is a record exists or not in the database like this,
public static boolean getConexion() { // change it to boolean because it returns boolean value
status = false;
String url = "jdbc:sqlserver://localhost:1433;databaseName=Colegio";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
System.out.println("No se pudo establecer conexión");
}
try {
cn = DriverManager.getConnection(url);
PreparedStatement ps = cn.prepareStatement("SELECT * FROM [dbo].[Login] where NombreUsuario=? AND Contrasenia=?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
if (rs.next) {
status = true;
}
} catch (SQLException e) {
}
return status;
}
public void setUsuario(String user, String pass) {
DB.user = user;
DB.pass = pass;
}
And in your view, you can pass the values to setUsuario() method and then call the getConexion() method which returns true if the user exists as shown below,
DA.DB.setUsuario(jtxtUsuario.getText(), jtxtPassword.getText());
if (DA.DB.getConexion()) {
new jfrmInterno().setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no coincide con ninguna cuenta","",JOptionPane.ERROR_MESSAGE);
jtxtUsuario.setText("");
jtxtPassword.setText("");
}
And I can't see the DA.DB.getStatus() method, so I have coded inside the getConexion() method to show what you are missing and this is not a GOOD PRACTICE to code inside the Database Connection and it should be in a separate class.

comment resolu problem sql.java.sql.SQLException

private void totaleActionPerformed(java.awt.event.ActionEvent evt) {
PreparedStatement ps;
ResultSet rst;
String query="SELECT SUM( montant_m) FROM `mnd` ";
String num_m = jTF1.getText();
try {
ps=Connecteur_db.connecterDB().prepareStatement(query);
// ps.setString(1, num_m);
rst=ps.executeQuery();
if(rst.next()){
String som_t = rst.getString("SUM(montant_m)");
jLabe_resultat.setText(""+som_t);
JOptionPane.showMessageDialog(null,""+som_t);
}
} catch (SQLException ex) { java.util.logging.Logger.getLogger(noveau_j.class.getName()).log(Level.SEVERE, null, ex);
}
}
While trying to execute this i am getting an error like "Caused by: java.sql.SQLException: Column 'SUM(montant_m)' not found.
at What is the problem here?? Please help me..
Sorry for my poor english
This is myconnecteur_db() class the connection
public static Connection connecterDB() {
Connection conx = null;
String pilot = "com.mysql.cj.jdbc.Driver";
try {
Class.forName(pilot);//chargement de driver
System.out.println("Driver ok");
String url = "jdbc:mysql://localhost:3307/tc";
String user = "root";
String pw;
pw = "root";
Connection con = DriverManager.getConnection(url, user, pw);
System.out.println("la connection est bien etablir");
return con;
} catch (Exception e) {
System.out.println("Echec connection!!");
e.printStackTrace();
return null;
}
}
I assume this is occuring at the line rst.getString("SUM(montant_m)")
SUM(montant_m) doesn't have a space before montant_m.
To make it easier, use the query:
SELECT SUM(montant_m) AS total FROM mnd
And then rst.getString("total")

Searching a record in SQL by an id in Java

In my SQL database single record consists of four rows: id, name, age and email. How to get a single record by typing in a JTextField id of that record? So later we can for example System.out.printIn(); it? I know that my question might be stupid for someone who is an SQL expert but I am only a beginner and after searching for this information in the tutorials I could not find it:(. Please help. Here is some of my source code:
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://some IP address/testdb";
String username = "some username";
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public EsquelTest() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
id = IDname.getText().toString();
try {
getConnection();
get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public static ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("Statement needed to get the whole record by owning only an ID");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while(result.next()){
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
return array;
}catch(Exception e){System.out.println(e);}
return null;
}
If you are asking for only SQL statement it is: select * from yourtable where id = theIdThatIsfromTextFieldHere
Yet, if you simply google it you will find thousands of answers. here for instance.
The SQL Statement would be SELECT * FROM yourtable WHERE id = yourid. So to embed it into your code it would look something like this:
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://some IP address/testdb";
String username = "some username";
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public EsquelTest() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
id = IDname.getText().toString();
try {
getConnection();
get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public static ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT * FROM {REPLACE WITH YOUR TABLE} WHERE id = "+idname);
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while(result.next()){
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
return array;
}catch(Exception e){System.out.println(e);}
return null;
}
Just a Tip: Don't name you function "get" as this is a commonly used keyword in other programming languages that only causes confusion.
Try it:
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://some IP address/testdb";
String username = "some username";
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public EsquelTest() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
id = IDname.getText().toString();
try {
getConnection();
for(String string:get(id)){
System.out.println(string);
}
// get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public static ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
// You should replace "YourTableName" With table in databace that you work with it
PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE id = '" + idName+"'");
//If type of your id in database is Int write this code :
// int id= Integer.parseInt(idName);
//PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE id = " + idName);
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
result.next();
//This array has all data in single recorde
array.add(result.getString("id"));
array.add(result.getString("name"));
array.add(result.getString("age"));
array.add(result.getString("email"));
// I removed this rows becuse you have only one record
// while(result.next()){
//
// array.add(result.getString("last"));
// }
System.out.println("All records have been selected!");
return array;
}catch(Exception e){System.out.println(e);}
return null;
}

While entering data to mysql getting connection null error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Here is the connection class
public class ConnectionManager {
Connection cn = null;
public Connection getConnection() throws ClassNotFoundException, SQLException {
String dbPath = "jdbc:mysql://localhost:3306/postjob";
String username = "root";
String password = "root";
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection(dbPath, username, password);
return cn;
}
public void closeConnection() throws SQLException{
cn.close();
}
}
Here is my service class
public class UserdetailsServices {
public Connection connection;
public ResultSet resultset;
// private Object resultSet;
public UserdetailsServices() {
try {
connection = new ConnectionManager().getConnection();
//here I am getting connection=null.
} catch (ClassNotFoundException ex) {
Logger.getLogger(UserdetailsServices.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(UserdetailsServices.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
* #param user
* #return
*/
public boolean registerUser(UserModal user) {
try {
java.sql.PreparedStatement psmt = connection.prepareStatement("insert into userdetails(role,name,gender,email,password,cpassword,contact) values(?,?,?,?,?,?,?)");
psmt.setString(1, user.getRole());
psmt.setString(2, user.getName());
psmt.setString(3, user.getGender());
psmt.setString(4, user.getEmail());
psmt.setString(5, user.getPassword());
psmt.setString(6, user.getCpassword());
psmt.setString(6, user.getContact());
int flag = psmt.executeUpdate();
if (flag > 0) {
return true;
} else {
return false;
}
} catch (SQLException ex) {
return false;
}
}
Insert have 7 fields but preparaedstatement is setting only 6 fields. It is missing setting contact value. That's why it is giving null error.
Instead of this
psmt.setString(6, user.getCpassword());
psmt.setString(6, user.getContact());
use this
psmt.setString(6, user.getCpassword());
psmt.setString(7, user.getContact());

simple login form using java and db2 . everything ok but still resultset empty

I am trying to make a simple login form. Every thing is working fine, connection is established, query is executed but ResultSet is still empty so always getting redirected to fail.jsp. No error no warning at all.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
modelclass md = new modelclass();
daoclass dao = new daoclass();
md.setName(name);
md.setPassword(password);
System.out.println("this just before the sql query on the main servlet page");
String sql = "Select * from USERADD where name = ? and password= ?";
String result = dao.guser(md, sql);
if (result.equals("success")) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("fail.jsp");
}
}
This is the DAO class which makes connection.
Data Access code(dao.java):
public class daoclass {
public static String username = "NickNeo";
public static String password = "123123";
public static String driver = "com.ibm.db2.jcc.DB2Driver";
public static String url = "jdbc:db2://localhost:50000/CITYLIFE";
public static Connection con = null;
public static PreparedStatement ps = null;
static {
try {
Class.forName(driver);
System.out.println("before connection");
con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Successfullll......!!!!!!");
} catch(Exception e) {
e.printStackTrace();
}
}
public String guser(modelclass obj, String sql) {
try {
System.out.println("entry into try block");
ps=con.prepareStatement(sql);
ps.setString(1, obj.getName());
ps.setString(2, obj.getPassword());
System.out.println("before query");
ResultSet rs = ps.executeQuery();
System.out.println("query executed");
int i = 0;
while(rs.next()) {
System.out.println("entered into while loop");
++i;
}
if (i >= 1) {
return "success";
} else {
System.out.println("this is inside else of while block");
return "fail";
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("this is the most outer fail statement");
return "fail";
}
}
the rs is always empty. tried many things but still getting rs as empty. please help

Categories