Below shows an error message I am receiving when trying to run my code:
sun.jdbc.odbc.JdbcOdbcStatement cannot be cast to java.sql.ResultSet
I don't understand why this error is occurring so could someone give me the reason why or even better give me a fix to the problem. Below is the entire code
public void actionlogin()
{
btnLogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String username = txtUserName.getText();
String password = txtPassword.getText();
String databaseUsername = "";
String databasePassword = "";
String dataSourceName = "securitySystem";
String dbUrl = "jdbc:odbc:" + dataSourceName;
try{
//Type of connection driver used
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Connection variable or object param: dbPath, userName, password
Connection con = DriverManager.getConnection(dbUrl, "", "");
Statement statement = con.createStatement();
statement.execute("select username, password from securitySystem.employees");
while (((ResultSet) statement).next()) {
databaseUsername = ((ResultSet) statement).getString("username"); //resultSet.getString("username");
databasePassword = ((ResultSet) statement).getString("password");
}
statement.close();
con.close();
}catch (Exception e){
System.out.print("Out!" +e);
}
You need to use statement.executeQuery and this will return the ResultSet.
So you need to write something like that:
ResultSet rs = statement.executeQuery("select....");
while (rs.next()) {
databaseUsername = rs.getString("username");
databasePassword = rs.getString("password";
}
Related
I'm trying to set up JDBC but I'm getting this error.
I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.
public class FilmLength {
public static void main(String[] args) throws SQLException {
Connection dbCon = null;
PreparedStatement st = null;
ResultSet rs = null;
String url = "jdbc:mysql//localhost:3306/sakila";
String username = "devuser";
String password = "Demo#123";
String query = "select * from film ";
try {
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(url,username,password);
st = dbCon.prepareStatement(query);
rs = st.executeQuery();
while(rs.next()) {
String title = rs.getString(1);
System.out.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
dbCon.close();
st.close();
rs.close();
}
}
}
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";
it should be
String url = "jdbc:mysql://localhost:3306/sakila";
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")
I have exactly same function in both Main method and other method JDBC connection is working fine. If I call the other function it throws error java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/wine:
I have included MySql Driver in library [Netbeans];
processRequest method:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String process = (String) request.getParameter("process");
String name = (String) request.getParameter("process");
String phone=(String) request.getParameter("phone");
String email = (String) request.getParameter("email");
String pwd = (String) request.getParameter("pwd");
PrintWriter out = response.getWriter();
out.println("Hello");
signup(out,process,name,email,phone,pwd);
}
signup method:
private static int signup(PrintWriter out,String process,String name,String email,String phone,String pwd){
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");
out.println("Process Not Found");
if (process == "signup") {
String query = "INSERT INTO user(name,phone,email,password,role) VALUES(?,?,?,?,1)";
stmt = con.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setString(3, email);
stmt.setString(4, pwd);
stmt.execute();
} else {
out.println("Process Not Found");
}
} catch (SQLException e) {
// do something appropriate with the exception, *at least*:
out.println(e);
e.printStackTrace();
return 0;
}
return 1;
}
Main Method :
public static void main(String[] args) {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String process = "signup";
String name = "Test";
String phone="45885";
String email = "Test#gmail.com";
String pwd = "dkjsdh";
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");
if (process == "signup") {
String query = "INSERT INTO user(name,phone,email,password,role,status) VALUES(?,?,?,?,1,1)";
stmt = con.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setString(3, email);
stmt.setString(4, pwd);
stmt.execute();
} else {
System.out.println("Process Not Found");
}
} catch (SQLException e) {
// do something appropriate with the exception, *at least*:
System.out.println(e);
e.printStackTrace();
}
}
There are two options that can be tried:
Class.forName("com.mysql.jdbc.Driver").newInstance() //older bug
and
Class.forName("com.mysql.jdbc.Driver");
In the comment I pasted the older bug solution when I meant to paste the second one.
Either way I am glad that it worked out for you
Please help me fix the error in this program. The problem is, even if I use the correct username and password, I can't create a verified login.
public class LoginDao {
public static boolean CheckUser(String Username,String Password)
{
boolean st =false;
String dbUsername, dbPassword;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DBConnection.getConnection();
String qry ="select *user where Username=? and Password=?";
PreparedStatement pst = con.prepareStatement(qry);
//pst.setString(1, Username);
//pst.setString(2, Password);
pst.executeQuery(qry);
ResultSet rs = pst.getResultSet();
while(rs.next()){
dbUsername = rs.getString("Username");
dbPassword = rs.getString("Password");
if(dbUsername.equals(Username) && dbPassword.equals(Password)){
System.out.println("Welcome");
st = true;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Check your SQL query? You are missing a FROM before * and user. Also you need to set the parameters when using a PreparedStatement, you have them commented out.
UPDATE
Try this:
public class LoginDao {
public static boolean CheckUser(final String username, final String password) {
final String qry ="SELECT * FROM user WHERE Username=? AND Password=?";
Connection con = null;
PreparedStatement pst;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DBConnection.getConnection();
pst = con.prepareStatement(qry);
pst.setString(1, username);
pst.setString(2, password);
pst.executeQuery(qry);
rs = pst.getResultSet();
// Notice I changed the 'while' by 'if'
if (rs.next()) {
return (username.equals(rs.getString("Username")) && password.equals(rs.getString("Password")));
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
// close/release (database resources) 'con', 'pst', 'rs' here
}
return false;
}
}
The below code always generates a NullPointerException error.
The connection:
Connection con;
java.sql.PreparedStatement st;
public void Connect()
{
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String user = "root";
String password = "";
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mpdb",user,password);
String sql = new String("SELECT * FROM 'dati' WHERE user =? and pass =?");
st = con.prepareStatement(sql);
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Connessione non riuscita");
ex.printStackTrace();
}
}
The login:
#SuppressWarnings("deprecation")
public void mouseClicked(MouseEvent arg0) {
TextFields tf = new TextFields();
Driver d = new Driver();
try{
String sql = new String("SELECT user,pass FROM 'dati' WHERE user =? and pass =?");
ps = d.con.prepareStatement(sql);
ps.setString(1,tf.ftf.getText()); //JFormattedTextField
ps.setString(2,tf.pf.getText()); //JPasswordField
rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "User successfully logged");
}else{
JOptionPane.showMessageDialog(null, "User not found");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
The select statement is wrong. Single quotes (') denote string literals in SQL, not object names (in your case - the table name). Since the SQL is invalid, no result set can be created, and hence the exception.
To resolve this, you should remove the quotes around 'dati':
String sql = "SELECT user,pass FROM dati WHERE user =? and pass =?"
I resolved with this code:
Execute connection:
package main;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class Driver {
Connection con = null;
public static Connection Join()
{
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String user = "root";
String password = "";
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mpdb",user,password);
return con;
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Connessione non riuscita");
ex.printStackTrace();
return null;
}
}
}
Login Button:
#SuppressWarnings("deprecation")
public void mouseClicked(MouseEvent arg0) {
TextFields tf = new TextFields();
String sql = new String("SELECT * FROM `dati` WHERE user = ? and pass = ?");
try{
ps = con.prepareStatement(sql);
ps.setString(1,tf.ftf.getText().trim());
ps.setString(2,tf.pf.getText().trim());
rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Login effettuato");
}else{
JOptionPane.showMessageDialog(null, "Utente o password non corretti");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
});
But now I've a new problem: the program do its work but it doesn't compare correctly the password. How do I have to proceed?