Derby Schema Error - java

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.

Related

Connection between Java and MySql

I am trying to make a connection between Java and my data base. I am using Eclipse and xampp. I am almost convinced that I have good config of Eclipse and xampp, but maybe I missed something. I searched a lot on the Internet, but I have not found the solution.
My error are:
SQLException: Could not create a connection to database server. Attempted to reconnect 3 times. Giving up.
SQLState: 08001
VendorError: 0
Xampp -
Xampp config
Eclipse -
I have jar files in the workspace folder.
Eclipse config
phpmyadmin -
I do not need a password to log into localhost/phpmyadmin and I have only one record in DB.
Code
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBC2 {
static String daneZBazy;
static String polaczenieURL = "jdbc:mysql://localhost:3306/heroes.db?
autoReconnect=true&useSSL=false";
static String login = "root";
static String password = "root";
public static void main(String[] args) {
// Question to DB
String query = "Select * FROM heroestab";
Connection conn = null;
try {
// Connection parameters
conn = DriverManager.getConnection(polaczenieURL, login, password);
// MySQL Driver
Class.forName("com.mysql.jdbc.Driver");
// Start question to DB
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
wyswietlDaneZBazy(rs);
}
conn.close();
}
//throws exception
catch (ClassNotFoundException wyjatek) {
System.out.println("Driver error");
}
catch (SQLException wyjatek) {
wyjatek.printStackTrace();
System.out.println("Login problem. Check, username, password, DB name, IP adress");
System.out.println("SQLException: " + wyjatek.getMessage());
System.out.println("SQLState: " + wyjatek.getSQLState());
System.out.println("VendorError: " + wyjatek.getErrorCode());
}
}
static void wyswietlDaneZBazy(ResultSet rs) {
try {
daneZBazy = rs.getString(1);
System.out.println("\n" + daneZBazy + " ");
daneZBazy = rs.getString(2);
System.out.println(daneZBazy + " ");
daneZBazy = rs.getString(3);
System.out.println(daneZBazy);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Please verify that both the username and password are correct.
I need the full stack trace from:
wyjatek.printStackTrace();
If the username (root) and password are incorrect, you will see the below line in your stacktrace:
Access denied for user 'root'#'localhost' (using password: YES)
If I remember correctly, with default xampp config, you can try this:
user: root
password: [blank]
static String login = "root";
static String password = "";
I can see my databases useing cmd:
C:\xampp\mysql\bin > mysql -u root -p
Enter
show databases ; and then I can see all databases which I have on localhost. When i
chose heroes and I can select * from heroes ;
Picture:
Database cmd

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. :)

SQL Server Java driver not working in class path

I have written a simple Java file to handle some SQL that is integrated with SQL server.
I downloaded the appropriate driver and stored the JAR in the correct class path however it only works if I run the file directly.
I have tried calling methods within the sql class from another class and i get the following error:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
I understand that this issue is well documented but it doesn't address my unique problem which is that it works within the file but not externally.
Another issue is that after the program is closed and rebuild my program forgets that the JAR was added as a library and requires me to add it again which is not good.
I have tried adding the class path by manually copying and pasting it into an XML config file but this is a hacky solution and I would rather do it properly. Please let me know where I am going wrong.
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.ow2.asm/asm/5.0.4/da08b8cce7bbf903602a25a3a163ae252435795/asm-5.0.4.jar!/" />
<root url="jar://$USER_HOME$/IdeaProjects/r3prototypingCFS/contracts/src/main/kotlin/com/r3corda/protocols/sqljdbc42.jar!/" />
</CLASSES>
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Use jdts driver ..it work with Sql Server 2014.
pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
and src
import java.sql.*;
public class Main {
public static void main(String[] args) throws SQLException {
// write your code here
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://localhost:1433/DATABASENAME";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "username";
String password = "yourpassword";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
Statement stmt = conn.createStatement();
String sql = "SELECT top 10 PhoneNumber,RegistrationDate\n" +
" \n" +
" FROM tblProductRegistration";
// ResultSet resultSet = stmt.executeQuery(sql);
// String selectSQL = "SELECT USER_ID, USERNAME FROM DBUSER WHERE USER_ID = ?";
//Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery(sql);
// preparedStatement.setInt(1, 1001);
// ResultSet resultSet = preparedStatement.executeQuery( );
//STEP 5: Extract data from result set
while(resultSet.next()){
//Retrieve by column name
String PhoneNumber = resultSet.getString("PhoneNumber");
String RegistrationDate = resultSet.getString("RegistrationDate");
//Display values
System.out.print("PhoneNumber: " + PhoneNumber);
System.out.print("RegistrationDate: " + RegistrationDate);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}

Cassandra JDBC preparedstatment error

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!

Java+MySQL with JDBC connector mistake

I'm trying to connect Java and MySQL with JDBC connector. So, I've downloaded connector from official cite, added it to classpath and added to the libraries of eclipse.
Now i'm using the code below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class LocalhostDBConnection
{
LocalhostDBConnection()
{
Connection connection;
try {
// Название драйвера
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
// Create a connection to the database
String serverName = "localhost";
String mydatabase = "AvtoKovriki";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "root";
String password = "";
connection = DriverManager.getConnection(url, username, password);
System.out.println("is connect to DB" + connection);
String query = "Select * FROM users";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.execute(query);
String dbtime;
while (rs.next())
{
dbtime = rs.getString(1);
System.out.println(dbtime);
} // end while
connection.close();
} // end try
catch (ClassNotFoundException e)
{
e.printStackTrace();
// Could not find the database driver
} catch (SQLException e)
{
e.printStackTrace();
// Could not connect to the database
}
}
}
But in string: ResultSet rs = stmt.execute(query); there is a mistake "Type mismatch: cannot convert from boolean to ResultSet".
I can't understand what the problem is. Need some help.
The Statement#execute method returns a boolean. You are looking for the Statement#executeQuery method, which returns a ResultSet.
Your code should be like this:
ResultSet rs = stmt.executeQuery(query);
Firstly, this has nothing to do with MySQL - you're not getting as far as running the code, and none of your code deals with MySQL-specific types. (My point is that you may or may not have the MySQL jar file in the right place; this error isn't due to that.)
If you look at the documentation for Statement.execute(String) you'll see that that returns boolean, not ResultSet. That's why you're getting the compile-time error.
You want executeQuery(String) instead - or you could call execute(String), and if it returns true, call getResultSet.
You need to use executeQuery(String sql) method
see javadocs for more details about the provided methods
http://docs.oracle.com/javase/6/docs/api/java/sql/Statement.html
stmt.execute(query);
returns boolean not ResultSet. You can get
ResultSet by using stmt.executeQuery() method for queries that won't
modify data in the database.
If you want to modify data in your Database use the executeUpdate() method, which will return an integer to indicate whether data has been modified or not.

Categories