What I'm trying to do seems simple but I get this error SQLITE_ERROR] SQL error or missing database (no such column: user1)
public String getIdUser(String name) {
try {
this.stat = conn.createStatement();
String sql = "SELECT id_user FROM User WHERE name = " + name;
ResultSet user = stat.executeQuery(sql);
return user.toString();
} catch (SQLException e) {
return null;
}
}
Replace
String sql = "SELECT FROM User WHERE name = " + name;
with
String sql = "SELECT * FROM User WHERE name = " + name; // you can also specify a column/columns instead of *
I see many problems in your code :
First
Your query should return something it should be :
SELECT col_name1, col_name2, ... FROM User ...
Or if you want to select every thing :
SELECT * FROM User ...
Second
String or Varchar should be between two quotes, your query for example should look like :
SELECT col_name1 FROM User WHERE name = 'name'
Third
I don't advice to use concatenation of query instead use Prepared Statement it is more secure and more helpful (I will provide an example)
Forth
To get a result you have to move the cursor you have to call result.next()
Fifth
Name of variable should be significant for example ResultSet should be ResultSet rs not ResultSet user
Your final code can be :
PrepareStatement prst = conn.prepareStatement("SELECT colName FROM User WHERE name = ?");
prst.setString(1, name);
ResultSet rs = prst.executeQuery();
if(rs.next()){
reuturn rs.getString("colName");
}
Without quoting the name string it's interpreted as column name, and thus the error you see. You could surround it with single quotes, but that's still generally a bad practice, and will leave the code vulnerable to SQL injection attacks.
Additionally, you're missing the select list (specifically, the id_user column), and missing getting it from the result set.
And finally, you forgot to close the statement and the result set.
If you put all of these corrections together, you should use something like this:
public String getIdUser(String name) {
try (PreparedStatmet ps =
conn.prepareStatement("SELECT id_user FROM User WHERE name = ?")) {
ps.setString(1, name);
try (ResultSet rs = stat.executeQuery()) {
if (rs.next()) {
return rs.getString(1);
}
}
} catch (SQLException ignore) {
}
return null;
}
I am doing practice for JDBC and using NetBeans 8.1. I created a table in MS Access and wrote a program. But the problem is that when I pass column index then my program runs successfully. But I pass column name as in my table in MS Access then there occurs an error that
Column not found
I am pasting code of my program and try to explain my problem further.
package database;
import java.sql.*;
public class Database {
public static void main(String[] args) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:personDSN";
Connection con = DriverManager.getConnection(url);
Statement st = con.createStatement();
String sql = "SELECT *FROM students";
ResultSet rs = st.executeQuery(sql);
while(rs.next())
{
String Name = rs.getString(2);
String add = rs.getString(3);
String pNum = rs.getString(4);
System.out.println(Name + " " + add + " " + pNum);
}
con.close();
}
catch(ClassNotFoundException | SQLException sqlEx)
{
System.out.println(sqlEx);
}
}
}
As you can see in while loop that i have passed column index in getString() function. In this case my program runs successfully. But when i pass name of field/attribute which is in my database table, then it gives me error that "Column not found". For example if I pass getString("name") then it gives me above error.
Please help me to solve my problem.
Note: I have checked again and again that there is no spelling mistake in my parameter opposite to actual table in ms access.
Problem was:
Can't get just inserted data from the table. From the error message it looks like it doesn't see the first column. I know the column is there and data was inserted. I checked database. I checked if column Number has some hidden space in name. No it doesn't.
Tried:
Debugged every line and everything was good together with inserting data to database.
Found the issue is almost at the end of the code:
rs1.next();
String s1 = rs1.getString(1);
I tried to write
rs1.first();
String s1 = rs1.getString(1);
or
rs1.first();
String s1 = rs1.getString("Number");
Below I posted my final code that is working correctly and I am able to insert data to the table and display on the browser.
package mypackage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.LinkedList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
#Path("/query")
public class CList {
private LinkedList<SMember> contacts;
public CList() {
contacts = new LinkedList();
}
#GET
#Path("/{CList}")
public Response addCLocation(#QueryParam("employeeId") String eId) throws SQLException{
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
PreparedStatement ps0 = null, ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try{
//Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
//Connection variables: dbPath, userName, password
con = (Connection)
DriverManager.getConnection(dbURL,"someusername","somepassword");
System.out.println("We are connected to database");
//SQL Statement to Execute
System.out.print(id);
s = con.prepareStatement("SELECT 1 FROM CList WHERE Number=?");
s.setString(1, eId);
rs = s.executeQuery();
//Parse SQL Response
if(!rs.next()) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) " +
"VALUES (?,?,?,?)");
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhone());
ps.executeUpdate();
ps = con.prepareStatement("SELECT Number, First_Name,
Last_Name, Phone_Number FROM CList
WHERE Number=" + eId);
rs1 = ps.executeQuery();
while(rs1.next()){
result = "[Added contact to contact list.
Number: " + rs1.getString(1) +
"][First_Name: " + rs1.getString(2) +
"][Last_name: " + rs1.getString(3) +
"][Phone_Number: " + rs1.getString(4) +
"]\n";
}
}
else {
result = "[Contact is already on the list]";
}
}
catch(Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
//Close Database Connection
ps0.close();
ps.close();
con.close();
}
}
catch(Exception e) {
System.out.println(e);
}
//Return the Result to Browser
return Response.status(1000).entity(result).build();
}
Table
1234 number is unique and it is a number I want to get.
You see number should be unique. So far I am taking data from the SMember class and it always insers the same data. Purpose of my question is just to ge the information I inserted few seconds ago.
Also, there is SMember class that I didn't post here and in its constructor I initialize number, first name, last name, and phone number. Testing purpose.
I made all recommended changes but problem remains the same.
There is several issues here.
The solution to your question is that you do not let the database generate keys, that is why you cannot ask for the generated keys later.
Look at this line of your code:
ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name, Phone_Number) VALUES ('"+sm.getEmployeeID()+"', '"+sm.getFirstName()+"', '"+sm.getLastName()+"', '"+sm.getPhone()+"')", Statement.RETURN_GENERATED_KEYS);
You later want to retrieve the Number column's value as a generated key. You however do pass a value for that column, namely the return value of sm.getEmployeeID(). If you pass a value, it will not get generated (assuming that this column is defined in database as being auto incremented.
Fixing this however, will not solve everything as your code has quite a lot of issues. Let me list the ones I can directly spot:
You initialize your variable sm by creating a new object. But you will still not have values for employee id, first name, last name or phone number as you nowhere set those values to sm (or do you do that in the default constructor?).
You are trying to use a prepared statement, this is good, but you are actually not doing that, this is very bad as it openes the ground for SQL injection. Instead of creating the query string like you are doing, you should use a fixed string like e.g INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?) and then set the values on the statement before executing it. That way nobody can mess with your database through that statement (read up on SQL injection, just google it to see the issue you would introduce).
Your employee id seems to be the eId parameter of your method. You should use that also in your select statement to see if it is already in your database (use a prepared statement here also) and in your insert statement later when the id is not already in the database.
If you are checking for a specific id, then insert that specific id, it is quite useless to retrieve some generated id. You already have defined your unique identifier. Use that one!
Edit: As your code is kind of a mess, I have cleaned this stuff a bit and fixed the issues that I could directly find. Check if this is helping you:
public Response addCLocation(String eId) throws SQLException {
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
Statement s = null;
PreparedStatement ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try {
// Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
// Connection variables: dbPath, userName, password
con = DriverManager.getConnection(dbURL, "someusername", "somepassword");
System.out.println("We are connected to database");
s = con.createStatement();
// SQL Statement to Execute
System.out.print(id);
PreparedStatement alreadyThere = con.prepareStatement("SELECT 1 FROM CList WHERE Number = ?");
alreadyThere.setString(1, eId);
System.out.println("0");
// Parse SQL Response
int i = 0;
if (rs.next() == false) {
SMember sm = new SMember();
ps = con
.prepareStatement("INSERT INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) VALUES (?,?,?,?)");
ps.setString(1, sm.getEmployeeID());
ps.setString(2, sm.getFirstName());
ps.setString(3, sm.getLastName());
ps.setString(4, sm.getPhone());
ps.executeUpdate();
}
else {
result = "[Contact is already on the list]";
}
}
catch (Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
// Close Database Connection
s.close();
ps.close();
con.close();
}
}
catch (Exception e) {
System.out.println(e);
}
// Return the Result to Browser
return Response.status(200).entity(result).build();
}
You are getting this error because your first query is wrong it is returning an empty resultset.
Firstly,
rs = s.executeQuery("SELECT 1 FROM CList WHERE Number='id'");
the above line in your code is not correct it should be like this:
**rs = s.executeQuery("SELECT 1 FROM CList WHERE Number="+id);**
then the correct query will be fired to database.
Secondly,there is problem in following code
if(rs.next() == false) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO CList (Number, First_Name, Last_Name,
Phone_Number) VALUES ('"+sm.getEmployeeID()+"',
'"+sm.getFirstName()+"', '"+sm.getLastName()+"',
'"+sm.getPhone()+"')",
Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
In the above code you should initialize the SMember, object currently in query they are going as null also the when you are using PreparedStatement you should use the query like this:
**ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhoneNumber());**
The Query statement maybe an issue "SELECT 1 FROM CList WHERE Number='id'",In select statement your id is taken as a String.we need to replace with value.
-->Try like this {"SELECT 1 FROM CList WHERE Number="+id},
-->One more thing "select 1 from table name" will print 1 for no of rows avail for your condition.
So my suggestion is
{"SELECT * FROM CList WHERE Number="+id}
try This!!
"SELECT 1 FROM CList WHERE Number='id'"
It looks like you're trying to actually select records where the Number value is 'id'. That may be causing the error when you try to do the "rs.next()" command on an empty result set. Are you instead trying to do something like
"SELECT 1 FROM CList WHERE Number=' " . id . "'"? Where "id" is a variable?
I want to create a method when i passed a value to the parameter, it will be passed to the sql statement.
here is what i've tried:
import java.sql.*;
import java.util.*;
import java.text.*;
public class cobadatabase{
protected String sn,fn,ln;
private Connection conn;
private PreparedStatement st;
public cobadatabase(String studentnumber)
{
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentrecords","root","");
st = conn.prepareStatement("SELECT * FROM student WHERE Student_Number=?");
ResultSet rs = st.executeQuery();
while (rs.next()){
sn = rs.getString(1);
fn = rs.getString(2);
ln = rs.getString(3);
SimpleDateFormat ft = new SimpleDateFormat("kk:mm:ss");
ft.format(rs.getTime("Total Time").getTime());
}
}
catch(Exception e){
e.printStackTrace();
}
i don't know what is wrong with my code. I just want to retrieve the data for printing
You haven't set parameter in prepareStatement
st = conn.prepareStatement("SELECT * FROM student WHERE Student_Number=?");
// You need to set the parameter for `?`
st.setString(1, studentnumber); // Add this code in between..
ResultSet rs = st.executeQuery();
And actually that is not a method.. that is a Constructor you are using.. And you are using it for wrong purpose..
Technically, the sole purpose of a Constructor is to initialize the attributes of the object being created, or initialize the environment for use..
For using database query, or doing any other kind of task, you should use a method, and invoke that..
I guess you mean something like that:
public String Func (String par1, String par2) throws SQLException {
String query;
query ="SELECT ... WHERE COLUMN_NAME between +"'"+par1+"'"+" AND " +"'"+par2+"'"+...";
rs = st.executeQuery(query); // get data or just Execute without getting results
Pay attention that Between a String there should be a " '' " (non-doubled quotes), whereas numeric values shouldn't.
I am trying to write a function for this button. I want to be able to pass it a textfield value and be able to go into my database to retrieve some information.....
Can somebody explain to me what is going on and provide me a solution to this madness?
Thank you all xD
I keep running into this stupid problem:
ACTION1 createdoracle.jdbc.driver.T4CConnection#484845aa
Exception:java.sql.SQLSyntaxErrorException: ORA-00904: "ART": invalid identifier
Code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//CLASS TYPE
//LIST ALL OFFERED CLASSES AND REVENUE
try{
String classtype = jTextField1.getText().trim();
if(classtype.equals("")){
JOptionPane.showMessageDialog(this, "Sorry Wrong input.... Please try again....");
}
else if(classtype != ""){
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection(
"jdbc:oracle:thin:#fourier.cs.iit.edu:1521:orcl",
"usr","pwd");
Statement stmt = conn.createStatement();
System.out.println("ACTION1 created"+conn+"\n\n");
String ct = jTextField1.getText().trim();
//String aa = "SELECT * FROM CLASS WHERE TYPE="+classtype;
//System.out.println(aa);
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE="+ct);
while (rset.next()) {
System.out.println(rset.getString("TITLE") + " ");
}
JOptionPane.showMessageDialog(this, "Class Type: "+classtype);
stmt.close();
conn.close();
System.out.println("Connection Closed");
}
catch(Exception sqle){
System.out.println("\nException:"+sqle);
}
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, "Please Retry input....", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Let me guess ... does the ct String start with "ART" (or some variation)?
If so, the problem is that SQL requires quotes around string literals. Your query probably looks to Oracle something like this:
SELECT * FROM CLASS WHERE TYPE=Art of War
but it should look like
SELECT * FROM CLASS WHERE TYPE='Art of War'
There are two ways to fix this:
Assemble the query with quote characters around ct.
Write the query as "SELECT * FROM CLASS WHERE TYPE=?", use a PreparedStatement instead of a Statement and use the setString method to supply the parameter value.
If done properly, the second approach is both more secure and more efficient. (The problem with string-bashing the query and using Statement is that you are potentially making yourself vulnerable to SQL injection attacks.)
You're passing the value as part of the query, and the string concatenation you're doing makes the SQL into:
SELECT * FROM CLASS WHERE TYPE=ART
(where ART is the value of ct from the textfield) so it's trying to find a column on the table called ART. At an absolute minimum you need to quote the string:
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE='" + ct + "'");
But really don't do this; as #Andreas_D says you're leaving yourself open to SQL injection. Always use prepared statements and bind variables:
String sql = "SELECT * FROM CLASS WHERE TYPE=?";
PrepareStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ct);
ResultSet rset = stmt.executeQuery();