Cassandra JDBC preparedstatment error - java

I have a following cassandra table "users" defined in keyspace "chemdb"
CREATE TABLE users (
userid text PRIMARY KEY,
passwd text,
fname text,
lname text,
creationdate timestamp,
isactive text
);
I created a java class JDBConnec.java to connect jsp with cassandra using jdbc:
package dbclasses;
import java.sql.*;
import java.lang.*;
import java.io.*;
public class JDBConnec {
public Statement stmt=null;
public ResultSet rs=null;
public Connection con=null;
public PreparedStatement pstmt = null;
public JDBConnec()
{
try
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra://127.0.0.1:9160/chemdb","okkkkk","12345");
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
The above class is succesfully compiling.
However in my jsp file, when I use the following code to select record from database by using Preparedstatements, I get the below mentioned error:
JDBConnec db = new JDBConnec();
String query = "select * from users where userid=?";
db.pstmt = db.con.prepareStatement(query);
db.pstmt.setString(1, "henry");
db.rs = db.pstmt.executeQuery();
It gives following error
InvalidRequestException(why:Undefined name userid in where clause ('userid EQ ?'))
Does cassandra jdbc driver support preparedstatments in jsp? Any thoughts on why this error is occuring. Thanks in advance.
Cassandra version: 2.0.8
Java: 7
Apache tomcat: latest downloaded yesterday

I was able to figure out problem. I just changed the query from
String query = "select * from users where userid=?";
to
String query = "select userid, passwd from chemdb.users where userid=?";
and it worked fine.
Thanks!

Related

DB Derby Database stops functioning once connected to DBeaver

Here is my application's code to create the database, connect to it, and make a table in the database called Accounts.
package eportfolio.application;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
*
* #author valeriomacpro
*/
public class HomePage extends javax.swing.JFrame {
public static String username;
public static String password;
public static int SelectedPost;
/**
* Creates new form HomePage
*/
public static boolean doesTableExists (String tableName, Connection conn)
throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
return result.next();
}
public HomePage() {
initComponents();
try
{
String databaseURL = "jdbc:derby:eportdatabase;create=true";
Connection con = DriverManager.getConnection(databaseURL);
Statement st = con.createStatement();
if (!doesTableExists("Accounts", con))
{
String sql = "CREATE TABLE Accounts (Username varchar(250), Password varchar(250)) ";
st.execute(sql);
System.out.println("Table Does Not Yet Exist!");
}
else if(doesTableExists("Accounts", con)) {
System.out.println("Table Already Exists!");
}
con.close();
} catch(SQLException e) {
do {
System.out.println("SQLState:" + e.getSQLState());
System.out.println("Error Code:" + e.getErrorCode());
System.out.println("Message:" + e.getMessage());
Throwable t = e.getCause();
while(t != null) {
System.out.println("Cause:" + t);
t = t.getCause();
}
e = e.getNextException();
} while (e != null);
}
}
Additionally, here is my code that interacts with the Accounts table.
try
{
String databaseURL = "jdbc:derby:eportdatabase;";
Connection con1 = DriverManager.getConnection(databaseURL);
Statement st = con1.createStatement();
String sql = " INSERT INTO Accounts VALUES ('"+txtNewUsername.getText()+"','"+txtNewPassword.getText()+"') ";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Account Info Saved!");
txtNewUsername.setText("");
txtNewPassword.setText("");
txtNewConfirm.setText("");
}
When I run the application, the code works fine. However, if I open DBeaver and connect it to my database, then the following error message comes up. Does not come up if DBeaver is closed, even if it is connected to the database.
Message:Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XJ040: Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
SQLState:XSDB6
Error Code:45000
Message:Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Why is this? Am I connecting the Database to DBeaver incorrectly? Or am I coding the database incorrectly in Netbeans? It could be that my drivers and db derby version are old, but I have not been able to find help on that online either. Also important to know that the table does show up in DBeaver, but does not update. I have to delete the database folder in my application's folder every time I want to use the application with DBeaver open. Any help appreciated.
By using this line of code:
String databaseURL = "jdbc:derby:eportdatabase;";
you are using Derby in the "embedded" configuration. With Embedded Derby, only one Java application at a time can use the database. Other applications that try to use it concurrently are rejected with the message
Another instance of Derby may have already booted the database
as you saw when you tried it.
There are other configurations in which Derby can be deployed and run; specifically there is a Client-Server configuration in which multiple applications may all run as clients, and may connect to the same Derby server, allowing the applications to run concurrently.
To learn more about these aspects of Derby, start here: https://db.apache.org/derby/docs/10.15/getstart/cgsquck70629.html

Creating a JAVA database from code. Statement wont execute and create table?

I'm not sure why my program isn't creating the table but I also need some ideas on how to fill the table with code like this once it's created? I need to add two more tables to this database too.
This is the error I'm getting :
java.sql.SQLSyntaxErrorException: Table/View 'PIZZASIZE' does not exist.
Caused by: ERROR 42X05: Table/View 'PIZZASIZE' does not exist.
Caused by: java.lang.RuntimeException: Exception in Application start method
Caused by: javafx.fxml.LoadException: file:/C:/Users/Allie/Documents/NetBeansProjects/Pizzeria_AllieBeckman/dist/run1674141987/Pizzeria_AllieBeckman.jar!/pizzeria_alliebeckman/FXMLDocument.fxml
This is the code that's supposed to create the table:
// connect to the derby URL using the given username and password
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/pizzeria;create=true", connectProps);
// current url for pre created database "jdbc:derby://localhost:1527/pizza"
// if connection is successful print that it succeeded.
System.out.println("database created");
stmt = connect.createStatement();
String sqlCreate = "CREATE TABLE PIZZASIZE "
+ "(id int NOT NULL, "
+ "size char(20) NOT NULL, "
+ "PRIMARY KEY (id))";
stmt.execute(sqlCreate);
Depending on the IDE you are using you could manually create the table in a console without going through the trouble of writing it in code. Here are some examples of how you could get the information from the tables.
Connection conn = CreatingDerbyDJB.dbConnection();
try{
String query = "INSERT INTO Items (Name,Color,ItemName,SchoolName, Description) VALUES(?,?,?,?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.execute();
conn.close();
}catch(Exception e)
{
e.printStackTrace();
} }
Here is what the Connection class should look like:
package main;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class CreatingDerbyDJB
{
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:LostAndFoundDB";
public static Connection dbConnection()
{
try
{
Class.forName(DRIVER).newInstance();
Connection c = DriverManager.getConnection(JDBC_URL);
return c;
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Approve this answer if this helped you, I'd be happy to explain things if it does not make sense. :)

Derby Schema Error

I am trying to insert data into Derby embedded database for my Desktop Application. But Derby is giving me error of Schema Not found error.
I have tried to solve error by creating schema as per username, but does not solve my problem. I searched internet, but none of given solution solved my problem.
package derbyd.ui;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class AddStudent extends javax.swing.JFrame {
private void bt_saveActionPerformed(java.awt.event.ActionEvent evt) {
String conURL = "jdbc:derby:myDB;create=true";
String user = "SOURABH";
String passwd = "pass";
Connection con = null;
Statement st = null;
String query;
ResultSet rs = null;
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection(conURL, user, passwd);
st = con.createStatement();
System.out.println("Connection established");
query = "INSERT INTO SOURABH.MyTable VALUES('"+txt_name.getText()+"','"+txt_surname.getText()+"')";
st.executeUpdate(query);
System.out.println("Added Successfully");
}
catch(Exception e)
{
System.out.println("Error ->"+e);
}
}
}
According to the Frequently Asked Questions of Apache Derby, you will see that:
A schema is only created by CREATE SCHEMA or creating an object (table etc.) in that schema (this is implicit schema creation).
In your code, you need create the table first and then work like a charm.
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection(conURL, user, passwd);
st = con.createStatement();
System.out.println("Connection established");
st.executeUpdate("CREATE TABLE MyTable" +
"(name VARCHAR(255), surname varchar(255))");
System.out.println("Table created");
query = "INSERT INTO SOURABH.MyTable VALUES(" +
"'" + txt_name.getText() + "','" + txt_surname.getText() + "')";
st.executeUpdate(query);
System.out.println("Added Successfully");
The output is:
Connection established
Table created
Added Successfully
If you run this statement more than once, you'll get an error because the table already exists. To deal with that, here.
the easiest solution is to configure your database properties and make schema the same as user name but in capital litters
ex:
schema APP
user app
hope my answer can help.

MySQL issue using Netbeans

OK so I made a mysql database on godaddy.com
I made an admin table there with 3 fields, ID,Username and Password.
In my program I connected to the database and it shows me the tables so I know its connected(Netbeans)
I downloaded Java JDBC driver and put it in the library of my project.
However when I run the program I get this error:
package testdata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestData {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
String Name = "rsg";
String Pass= "dfgd";
String Host = "blahhhhhhhhhhhhhhh";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="DELETE FROM ADMIN";
stmt.executeUpdate(query);
String sql = "SELECT * FROM ADMIN";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
rs.updateInt("ID", 1 );
rs.updateString("Username", "CHRIS");
rs.updateString("Password", "CHRIS");
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
}
}
error is:
java.sql.SQLException: No suitable driver found for ****THIS IS MY HostName****
at java.sql.DriverManager.getConnection(DriverManager.java:604)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at testdata.TestData.main(TestData.java:28)
add mysql conntector jar file in your classpath.
I thing it's an issue with your host address. Check how should it look in MySql documentation
use
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DatabaseUrl, DataDaseusername, DatabasePass);
example for DatabaseUrl is given below
jdbc:mysql://192.168.100.100/databasename
mysql-connector-java-5.1.22 download from mysql.com
Insure you have add the jar folder in your project.
I believe its is looking for com.mysql.jdbc.Driver
make sure your connection string is correct for an example "jdbc:mysql://remot-example-mysql999.servage.net:3306/databasename?zeroDateTimeBehavior=convertToNull";
Your JDBC connection string is not correct (you cannot simply use the hostname). You need to use a JDBC URL, which for MySQL takes the form:
"jdbc:mysql://<hostname>:<port>/<database>"
Where <port> is optional if your server is running on the default, and is also optional. Change your getConnection method to this:
connection = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "3306", "YourDBName"),
Name, Pass);
Replace "YourDBName" with the name of the database you are trying to connect to. You also need to have the MySQL driver JAR in your classpath.

Database error: relation does not exist

I have a postgres database and a table named "state_master". I'm simply fetching the data from this table by the following code.
import java.sql.*;
public class Test1
{
public static void main(String... s1)
{
try{
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432:secc_db","postgres", password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from state_master");
}catch(SQLException e){ System.out.println(e);}
catch(Exception i){System.out.println(i);}
}
}
All I get is an error: relation state_master does not exist. Please help me to sort out this problem.
The erroe means the table state_master is not exist in the user(Database) postgres. Check whether you have created the table state_master in your database or not. If not first create the table then try to execute the program.
Your connect url is not correct. you are using colon(:) for specifying the database.
It should be a slash(/) like : "jdbc:postgresql://localhost:5432/secc_db"

Categories