I tried to create a login form and it is showing Column index is out of range. I have created two columns and I have used two columns but it is showing error.
String url = "jdbc:mysql://localhost:3306/login_form?useSSL=false";
String name = "Vzlys";
String Pass = "Vzlys#1995";
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,name,Pass);
st = con.prepareStatement("select * from login where username = ? and password = ?");//here login is my table name
st.setString(1,txtusername.getText());
st.setString(2,txtpassword.getText());//error occurs here
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"Welcome");
ferrysql f = new ferrysql();
f.setVisible(true);
con.close();
st.close();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
In your code:
st = con.prepareStatement("query");
Means your query is : query
But if you use ;
String query= "select * from table A where column1 = ?";
st = con.prepareStatement(query);
Note: in this staement query is not within inverted commas.
Hope this will help.
st = con.prepareStatement("query");
Above line shows that your query is "query" not the variable, which you might have been used in your program
It may be due to your txtpassword.getText() is null at line
st.setString(2,txtpassword.getText());
print both txtusername and txtpassword to check both filed contains data or not before using at preparedStatement
If you are checking user name and password then you have to use following query
PreparedStatement st = con.prepareStatement("select * from user where
(userName = ? and password = ?");
st.setString(1,txtusername.getText());
st.setString(2,txtpassword.getText());
This should work
Related
I built an app that counts some tax forms in a table and has to insert the number in another table.
When I count the tax forms in the first table I do it with this sql query :
select count(distinct cui) from dec_declaratii where id > 142321849 and
tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern
in ('DUK_VLD', 'GEN_MSJ')";
When I run it from Oracle Toad it works but when i put it in java and I try to get the result with rs.getString("count(distinct cui)") it gives me this error :
java.sql.SQLException: Invalid column name
Why is this happening ?
What can I do to make it work ?
I tried writing count(distinct cui) with capital letters and if I write count(*) it works but I need the distinct number of tax forms.
public class Baza {
int idmin = 142321849;
int rezultat = 391320;
String host = "xxx";
String user = "xxx";
String pass = "xxx";
String user2 = "xxx";
String pass2 = "xxx";
String host2 = "xxx";
String nr = "0";
public void conectare() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(host, user, pass);
Statement st = con.createStatement();
String sql = "select count(distinct cui) from dec_declaratii where id
> 142321849 and tip_declaratie='D212' and anul_duk>=2019 and
cod_stare_prelucrare_intern in ('DUK_VLD', 'GEN_MSJ')";
ResultSet rs = st.executeQuery(sql);
while(rs.next()) {
nr = rs.getString("count(DISTINCT CUI)");
System.out.println(nr);
}
}catch(Exception e) {System.out.println(e);}
int nr2 = Integer.parseInt(nr);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(host2, user2, pass2);
Statement st = con.createStatement();
String sql = "update nr_tot_dec_212 set nr_dec='"+nr+"', data=sysdate
where id=1";
st.executeUpdate(sql);
}catch(Exception e) {System.out.println(e);}
}
}
I would like to get the result of the query : select count(distinct cui) from dec_declaratii where id > 142321849 and tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern in ('DUK_VLD', 'GEN_MSJ')"; in a Java variable. It gives me this error:java.sql.SQLException: Invalid column name
use alias for name the column of your count
select count(distinct cui) as cnt from dec_declaratii where id > 142321849 and
tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern
in ('DUK_VLD', 'GEN_MSJ')";
My Jtable is connected to the database that I made so that it can show all the data right in my GUI. But Im trying to fetch the data from my JTable to the JTextField. Its like when you click the row of the table the data from the database thats inside the table will go to the TextField. But when I clicked the table it shows an error like this:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'NO.='1
RASCHEL" at line 1
I've been searching for the answer but I was unable to find one. Please help me I've been stuck to this error since friday.
table = new JTable();
scrollPane.setViewportView(table);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
int row = table.getSelectedRow();
String table_click = (table.getModel().getValueAt(row, 0).toString());
try {
String query = "SELECT * FROM `raschel` where MACHINE NO.='" + table_click + "'";
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String machine = rs.getString("MACHINE NO.");
String type = rs.getString("TYPE");
String product = rs.getString("PRODUCT");
txtMachine.setText(machine);
txtType.setText(type);
txtProd.setText(product);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
});
The column you are using MACHINE NO. contains a space and a dot in the end to work with like names you have to put the name between two :
`MACHINE NO.`
So your query should look like this :
String query = "SELECT * FROM `raschel` where `MACHINE NO.`='" + table_click + "'";
But this still not secure agains syntax error or SQL Injection so instead you can use :
String query = "SELECT * FROM `raschel` where `MACHINE NO.` = ?";
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root","");
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, table_click);//<<-----------set the parameter like this
ResultSet rs = ps.executeQuery();
You sould not use blanks and dots in column names. If you have to use blank and dot you have to escape the column name with a backtick:
String query = "SELECT * FROM `raschel` where `MACHINE NO.`='"+table_click+"'";
But i would strongly recommand to not use blanks and dots (or other special character) in column or table names.
String query = "SELECT * FROM `raschel` where MACHINENO='"+table_click+"'";
Also change to prepared statements to prevent SQL injection
Try this on your
String query = "SELECT * FROM `raschel` where `MACHINE NO.`='"+table_click+"'";
I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.
For example:
If TextField1 == to the data in the database.
Output: Swept by GSW.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list WHERE id = ?";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
}
}
}catch(SQLException exc){
System.out.println("Not Found!");
}
Kindly Check the Image Output.
I attached the image file below.
Sample Output
Here are some mistake I see
You use a parameter in the query, "SELECT * FROM item_list WHERE id = ?";so use a PreparedStatement
Set the parameter to that PreparedStatement ps = connection.preparedStatement(query); with ps.setInt(1, Integer.parseInt(TF[0].getText()));
Don't catch the exception without logging it, here your query as a syntax error but you don't know it.
careful with uppercase in the database field name "Id"
This might not be everything ...
And of course, now that you get only the row with that ID, you can simply check if there is at least one row return to validate that it exists.
First of all, you need to log a stack trace of an exception that is thrown. At least you can use exc.printStackTrace() in your catch section.
Second, your issue is that you declared a parameter for your SQL query, but you have not put any value to it.
PreparedStatement p = con.prepareStatement("SELECT * FROM item_list WHERE id = ?");
p.setString(1, TF[0].getText() ); //VALUE_FROM_YOUR_TEXT_INPUT
You don't need to iterate over all result set to check if a user with such id exists. You can just check that result set is not empty.
you can use intValue() for Integer object obvious if your object is not null
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()).intValue() == id){
System.out.println(id);
}
}
You're not setting the value of the id parameter in the statement. Not familiar with Java but in C# it would be something like
statement.Parameters.AddWithValue("#id", id)
Thank You guys! I've been trying and reading all your suggestions, and I've found and debugged it. Thanks to the one said that I need to check what message I can get in the catch.
Appreciated all your help.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
JOptionPane.showMessageDialog(null, "FOUND!");
}
else{
JOptionPane.showMessageDialog(null, "Not Found!");
}
}
}catch(SQLException exc){
JOptionPane.showMessageDialog(null, exc.getMessage());
}
ID Found!
I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting unexpected output in program
To be frank,this question may be silly to ask, but I'm a novice in Java.
This is my Table emp(name,id,address,date).
Now I'm going to match a certain employee's corresponding password.
String sql = "select emp_id,password from regid";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
// here will be iterate function using resultset,i guess
// what should be the best logic to check the name and password...any inputs
//in terms of code
if(if (employee.equals(rs.getString("emp_id")) && password.equals(rs.getString("password")))){
You are Mr. emp // in terms of code
}
else{
Who are You ?? //in terms of code
}
}
Any inputs will be highly appreciated.
Use a PreparedStatement to create your query. So your parameterized query for the PreparedStatement would be something like this:
SELECT * from regid WHERE emp_id = ? AND password = ?
Plug in the paremeter values and execute your statement. So it would be something like this:
PreparedStatement ps = null;
ResultSet rs = null;
boolean validUser = false;
try{
ps = connection.prepareStatement("SELECT * from regid WHERE emp_id = ? AND password = ?");
ps.setString(1, [user_id_input]);
ps.setString(2, [user_pw_input]);
rs = ps.executeQuery();
validUser = rs.next();
}finally{
//Release your resources
}
if(validUser){
//user is validated
}
As a side note, I would also suggest to validate your user's input before feeding it to your query.
You are selecting the data for all employees and looking through them for a match.
Much better to have the database filter it:
select count(*) from regid where emp_id = ? and password = ?
Then you only need to check if this returns 0 or 1.
Also, password is hopefully just a password hash.
fetching all data from database make your application performance slow, So fire following query retrieve one record.
boolean status = false;
String emp_name = "";
String emp_password = "";
String sql = "select * from regid where emp_id='"+emp_id+"' AND password='"+password+"'";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
if(emp_id.equals(rs.getString("emp_id")) && password.equals(rs.getString("password")))
{
// fetch employee data
status = true;
}
}
if(status)
{
// login correct
}
else
{
// login incorrect
}
Query your database with "select emp_id,password,... from regid where emp_id=? and password=?"
Create a PreparedStatement and set emp_id and password. it will return you 1 row if emp_id and password match.
You actually shouldn't be matching the password in the result set. Your sql query should be something like
select emp_id from regid where password='userpassword'
where userpassword is the password you got from the screen your using