Unknown column 'table.column' in 'field list' - java

I have updated one of my tables to include the column canttouchthis using the MySQL Workbench.
From the MySQL Workbench there is no problem writing sql against the column canttouchthis. But, in my code I get the following error on any instance of said column, but the remained of the columns work just fine, such as groups.id
Unknown column 'groups.canttouchthis' in 'field list'
Even a simple select statement like the following doesn't work:
try {
String sql = "SELECT groups.canttouchthis FROM groups";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
data.addProperty("got_data", rs.getLong(groups.canttouchthis));
}
} catch (SQLException ex) {
StackTrace.print(ex);
}
I have tried reseting my Java Servlet Container server to no avail

I realized that I was passing the wrong database connection to this point.
Thanks for your vigilance, I would delete this question if I could.

You can create new alias like SELECT gp.canttouchthis AS ctt FROM groups as gp after user "ctt" in while loop

Related

Getting SQL Exception when trying to get the last auto-incremented value

I've been trying everything, nothing is working, I'm new to mysql and databases and I want to get the last auto-incremented id (primary key) (user_id) from a table, from java. So this: SELECT MAX(user_id) FROM database_user; works fine in mysql, I got that, but why can't I get the same thing from java??
PreparedStatement st = connection.prepareStatement("SELECT MAX(user_id) from database_user");
st.executeUpdate();
ResultSet rs = st.executeQuery();
int uid = rs.getInt(1);
System.out.println(uid);
This gives me java.sql.SQLException: (conn=213) the given SQL statement produces an unexpected ResultSet object
This isn't the only thing I tried, it's just the last one so far. If anyone could just shed some light I would greatly appreaciate it.
You are missing rs.next(); between executing the query and fetching from the result set. This is needed, to move the result set to the first row.
You also shouldn't have st.executeUpdate(). Just executing once is enough.

Delete row from table

I want to delete the current row displayed in jframe from the table contact
I wrote the code
try
{
conn = java.sql.DriverManager.getConnection(connectionURL, "usrnme", "pswd");
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);//also tried with ResultSet.TYPE_SCROLL_SENSITIVE
rs.deleteRow();
rs.next();//it may or may not include in code
}
catch(Exception e){System.out.println( "JDBC error: " + e );}
sql query
String sql="SELECT * FROM contact order by first_name, last_name";
rs=stmnt.executeQuery(sql);
but it throws an exception while running
JDBC error: java.sql.SQLException: 'deleteRow' not allowed because the ResultSet is not an updatable ResultSet.
Help me!
I suggest to do it totally in SQL, where you need to additionally select the (internal) rowid of every row
SELECT c.*, c.rowid FROM contact c ORDER BY first_name, last_name
and afterward delete a row by it row id
DELETE FROM contact c WHERE c.rowid = (?)
this works for Oracle, but every Databasetype does use internal rowid's. For MYSQl you get the rowid by using #rowid as far as I remember
Instead of ResultSet.TYPE_SCROLL_INSENSITIVE, try ResultSet.TYPE_SCROLL_SENSITIVE. That might do the trick. If that doesn't work, try an SQL DELETE statement (w3schools.com) instead to delete the row.
Edit: Now that I reread your code: you need to move to the next row before you call deleteRow. Opening a statement sets the cursor before the first row. If your call to next returns true, your cursor points to the first row. Only if the cursor points to a valid row can you delete the row. HTH.
To make use of updatable ResultSet , your table must contain primary key column. It is the link between data present in ResultSet and DB. Since I infer from your comments your table does not contain primary key, you can delete row using sql query.
String sql = "DELETE FROM contact WHERE first_name='test'";
stmt.executeUpdate(sql);

SQLException: Unsupported feature

I am trying to get Generated key from sequnce.(Using Servlets & Oracle10)
Following is my code:
query ="insert into TABLE_NAME(COL1,COL2,COL3) values(sysdate,?,SEQ_NAME.nextval)";
PreparedStatement pstmt = con.prepareStatement(query,new String[]{"COL3"}); //Getting error on this line
pstmt.setString(1,Str2);
pstmt.executeUpdate();
ResultSet keyset = pstmt.getGeneratedKeys();
if(keyset.next())
{
genKey = keyset.getString(1);
}
But I am getting the Exception:
java.sql.SQLException: Unsupported feature
Few days ago this code was working fine. So what might be the reason that this code is not working now? (I haven't changed the JDBC driver war file)
Thanks in advance.
Is there another way of getting the value generated by sequence in the query?
Download the latest JDBC drivers, I think you need at least the 10.2.0.1 drivers and the db also need to be 10.2+
http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc101040.html
or first get the sequence value
String sqlForSeq = "select SEQ_NAME.NEXTVAL from dual";
ResultSet rs = stmt.executeQuery(sqlForSeq);
if (rs.next()) {
logSeq = rs.getString("NEXTVAL");
}

Creating a "Java DB" database and associated tables in main checking to see if they exist?

I'm creating an applicaation on Netbeans 7! I'd like my application to have a little code in main so that it can create a Java DB connection checking to see if the database and the associate tables exist, if not create the database and the tables in it. If you could provide a sample code, it'd be just as great! I have already looked at http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/ but I'm still not sure how to check for an existing database before creating it!
I'd like my application to have a little code in main so that it can create a Java DB connection checking to see if the database and the associate tables exist, if not create the database and the tables in it.
You can add the create=true property, in the JDBC URL. This creates a Derby database instance if the database specified by the databaseName does not exist at the time of connection. A warning is issued if the database already exists, but as far as I know, no SQLException will be thrown.
As far as creation of the tables is concerned, this is best done on application startup before you access the database for typical transactional activity. You will need to query the SYSTABLES system table in Derby/JavaDB to ascertain whether your tables exist.
Connection conn;
try
{
String[] tableNames = {"tableA", "tableB"};
String[] createTableStmts = ... // read the CREATE TABLE SQL statements from a file into this String array. First statement is for the tableA, and so on.
conn = DriverManager.getConnection("jdbc:derby:sampleDB;create=true");
for(int ctr =0 ; ctr < tableNames.length; ctr++)
{
PreparedStatement pStmt = conn.prepareStatement("SELECT t.tablename FROM sys.systables t WHERE t.tablename = ?");
pStmt.setString(1, tableNames[ctr]);
ResultSet rs = pStmt.executeQuery();
if(!rs.next())
{
// Create the table
Statement stmt = conn.createStatement();
stmt.executeUpdate(createTableStmts[ctr]);
stmt.close();
}
rs.close();
pStmt.close();
}
}
catch (SQLException e)
{
throw new RuntimeException("Problem starting the app...", e);
}
Any non-existent tables may then be created. This is of course, not a good practice, if your application has multiple versions, and the schema varies from one version of the application to another. If you must handle such a scenario, you should store the version of the application in a distinct table (that will usually not change across versions), and then apply database delta scripts specific to the newer version, to migrate your database from the older version. Using database change management tools like DbDeploy or LiquiBase is recommended. Under the hood, the tools perform the same operation by storing the version number of the application in a table, and execute delta scripts having versions greater than the one in the database.
On a final note, there is no significant difference between JavaDB and Apache Derby.
I don't know how much Oracle changed Derby before rebranding it, but if they didn't change too much then you might be helped by Delete all tables in Derby DB. The answers to that question list several ways to check what tables exist within a database.
You will specify the database when you create your DB connection; otherwise the connection will not be created successfully. (The exact syntax of this is up to how you are connecting to your db, but the logic of it is the same as in shree's answer.)
The create=true property will create a new database if it is not exists. You may use DatabaseMetadata.getTables() method to check the existence of Tables.
Connection cn=DriverManager.getConnection("jdbc:derby://localhost:1527/testdb3;create=true", "testdb3", "testdb3");
ResultSet mrs=cn.getMetaData().getTables(null, null, null, new String[]{"TABLE"});
while(mrs.next())
{
if(!"EMP".equals(mrs.getString("TABLE_NAME")))
{
Statement st=cn.createStatement();
st.executeUpdate("create table emp (eno int primary key, ename varchar(30))");
st.close();;
}
}
mrs.close();
cn.close();
Connection conn = getMySqlConnection();
System.out.println("Got Connection.");
Statement st = conn.createStatement();
String tableName = ur table name ;
String query = ur query;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
System.out.println("Exist");;
}
catch (Exception e ) {
// table does not exist or some other problem
//e.printStackTrace();
System.out.println("Not Exist");
}
st.close();
conn.close();

Java SQL "ERROR: Relation "Table_Name" does not exist"

I'm trying to connect netbeans to my postgresql database. The connection seems to have worked as I don't get any errors or exceptions when just connecting, methods such as getCatalog() also return the correct answers.
But when I try to run a simple SQL statement I get the error "ERROR: relation "TABLE_NAME" does not exist", where TABLE_NAME is any one of my tables which DO exist in the database. Here's my code:
Statement stmt = con.createStatement();
ResultSet rs;
String query = "SELECT * FROM clients";
rs = stmt.executeQuery(query);
I was thinking that netbeans might not be finding the tables because it's not looking in the default schema (public), is there a way of setting the schema in java?
EDIT: My connection code. The database name is Cinemax, when I leave out the statement code, I get no errors.
String url = "jdbc:postgresql://localhost:5432/Cinemax";
try{
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException cnfe) {
System.err.println("Couldn't find driver class:");
cnfe.printStackTrace();
}
Connection con = DriverManager.getConnection( url,"postgres","desertrose147");
I suspect you created the table using double quotes using e.g. "Clients" or some other combination of upper/lowercase characters and therefor the table name is case sensitive now.
What does the statement
SELECT table_schema, table_name
FROM information_schema.tables
WHERE lower(table_name) = 'clients'
return?
If the table name that is returned is not lowercase you have to use double quotes when referring to it, something like this:
String query = "SELECT * FROM \"Clients\"";
You could check these possibilities:
String query = "SELECT * FROM clients";
String query = "SELECT * FROM CLIENTS";
String query = "SELECT * FROM \"clients\"";
String query = "SELECT * FROM \"CLIENTS\"";
String query = "SELECT * FROM Clients";
Maybe one of those would work.
Besides CoolBeans' suggestion, you may also be connecting to the db as a different user who does not have permission on the relevant db or schema. Can you show the connection string?
Funny thing is i was experiencing the same thing as i had just started on netbeans and postgressql db, and the error was fixed after noting that the issue was that my tables in postgressql had capital letters in my naming convention which me and my jdbc query statement for INSERT was failing to find the table. But after renaming my tables in the db and fixing the column names as well am good to go. Hope it helps.

Categories