Access is Denied, Issue in embedded Derby - java

I'm having a problem with my derby engine.
When I make a new database , create new tables and insert or display rows , everything works fine. And when I try to use the database in my practice example , the database works fine and I'm able to insert and select data from the table.
Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
public class Restaurants
{
private static String dbURL = "jdbc:derby:c:\\Apache\\db-derby-10.14.2.0-bin\\bin\\myDBExample;create=true";
private static String tableName = "restaurants";
// jdbc Connection
private static Connection conn = null;
private static Statement stmt = null;
public static void main(String[] args)
{
createConnection();
//insertRestaurants(5, "LaVals Leb", "Berkeley");
//insertRestaurants(6, "House Leb", "New York");
selectRestaurants();
shutdown();
}
private static void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
}
catch (Exception except)
{
except.printStackTrace();
}
}
private static void insertRestaurants(int id, String restName, String cityName)
{
try
{
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (" +
id + ",'" + restName + "','" + cityName +"')");
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void selectRestaurants()
{
try
{
stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("select * from " + tableName);
ResultSetMetaData rsmd = results.getMetaData();
int numberCols = rsmd.getColumnCount();
for (int i=1; i<=numberCols; i++)
{
//print Column Names
System.out.print(rsmd.getColumnLabel(i)+"\t\t");
}
System.out.println("\n-------------------------------------------------");
while(results.next())
{
int id = results.getInt(1);
String restName = results.getString(2);
String cityName = results.getString(3);
System.out.println(id + "\t\t" + restName + "\t\t" + cityName);
}
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void shutdown()
{
try
{
if (stmt != null)
{
stmt.close();
}
if (conn != null)
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
}
}
catch (SQLException sqlExcept)
{
}
}
}
This code works fine but when I try to create a connection to the same database again with ij , I get an error in my command prompt like this:
In the image, the upper part is when I first make my database but after that when I use it in eclipse, it gives me this error. Even using a db in eclipse once will result in this error.
What is the issue? Why is derby engine not getting the access granted to it?
Any help is appreciated.

I suspect that you confused the database modes here. In your question's title you mention "embedded Derby", but you're code is using the ClientDriver and the create=true attribute, which does create the DB if it doesn't exist, but it doesn't start the server.
If you don't want to start the server, you can just use the EmbeddedDriver.
Another point where you might run into problems is with the shutdown=true attribute. You're using the entire DB URL (dbURL) including the filename, but if you want to shut down the server from your code, you should omit the filename, like this : jdbc:derby:;shutdown=true.
You can check out the Derby developer docs for information on using these attributes, and the Embedded Derby tutorial for using Derby in embedded mode, sou you won't have to worry about starting the server.

Found out the issue. I had to start the derby as a network server on the port by using the following command:
startNetworkServer.bat

Related

Java access DataBase connection

I want to learn how to connect DB with java. I write following code for that:
package login;
import java.sql.*;
public class DBTest {
public static void main(String[] args) {
try {
Class.forName("sun.odbc.jdbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:Test");
Statement s = c.createStatement();
String sql = "select * from Table1";
ResultSet result = s.executeQuery(sql);
while (result.next()) {
System.out.println("\n" + result.getString(1) + "\t" + result.getString(2));
}
} catch (Exception e) {
System.out.println("exception generated:" + e.getMessage());
}
}
}
but I get exception:
run:
exception generated:sun.odbc.jdbc.JdbcOdbcDriver BUILD SUCCESSFUL
(total time: 0 seconds)
I cerated database named exp.accdb. How I get solve this problem?
Don't you have to put in the database credentials, i.e. the hostname, username and password?
For instance:
c = DriverManager.getConnection(host, username, password);
You can check if it is connected during debugging by doing this as well:
if (c != null) {
System.out.println("Connection established");
}

How do I call data from a table in a database into a java class in netbeans?

first time posting so sorry if my question is slightly strange.
So I have a project in school that requires us to create java classes using netbeans that open up a window with three options, check stock, purchase item and update stock.
We had a class called stockdata that held the details of 5 different items for us to use in our three classes to check, purchase and update items. The latest stage of our coursework requires us to create a derby database and enter the items into a table.
I have done this with no issues but I am having a problem getting the items from the table back into my classes to use. We were given the following code but I can't get it to work, even using the commented hints.
package stock;
// Skeleton version of StockData.java that links to a database.
// NOTE: You should not have to make any changes to the other
// Java GUI classes for this to work, if you complete it correctly.
// Indeed these classes shouldn't even need to be recompiled
import java.sql.*; // DB handling package
import java.io.*;
import org.apache.derby.drda.NetworkServerControl;
public class StockData {
private static Connection connection;
private static Statement stmt;
static {
// standard code to open a connection and statement to an Access database
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("UserDB").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "use", "use");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
System.out.println(cnfe);
} catch (SQLException sqle) {
System.out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
// You could make methods getName, getPrice and getQuantity simpler by using an auxiliary
// private String method getField(String key, int fieldNo) to return the appropriate field as a String
public static String getName(String key) {
try {
// Need single quote marks ' around the key field in SQL. This is easy to get wrong!
// For instance if key was "11" the SELECT statement would be:
// SELECT * FROM Stock WHERE stockKey = '11'
ResultSet res = stmt.executeQuery("SELECT * FROM Stock WHERE stockKey = '" + key + "'");
if (res.next()) { // there is a result
// the name field is the second one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
return res.getString(2);
} else {
return null;
}
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
public static double getPrice(String key) {
// Similar to getName. If no result, return -1.0
return 0;
}
public static int getQuantity(String key) {
// Similar to getName. If no result, return -1
return 0;
}
// update stock levels
// extra is +ve if adding stock
// extra is -ve if selling stock
public static void update(String key, int extra) {
// SQL UPDATE statement required. For instance if extra is 5 and stockKey is "11" then updateStr is
// UPDATE Stock SET stockQuantity = stockQuantity + 5 WHERE stockKey = '11'
String updateStr = "UPDATE Stock SET stockQuantity = stockQuantity + " + extra + " WHERE stockKey = '" + key + "'";
System.out.println(updateStr);
try {
stmt.executeUpdate(updateStr);
} catch (SQLException e) {
System.out.println(e);
}
}
// close the database
public static void close() {
try {
connection.close();
} catch (SQLException e) {
// this shouldn't happen
System.out.println(e);
}
}
}
Sorry if this seems a stupid question but I am fairly new to Java and was making good progress until this roadblock.
Thanks in advance!
Alex
Searching for "java sql" on Google delivers this link: https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html
From a connection you can create a statement (you can find this in the link and in your code) , then fetch a result set and loop over that with rs.next(). That should get your started.
Of course you have to make sure that the driver and database are there/running, just saying...
Here netbeans has nothing to do with database. This is a Java-based integrated development environment(IDE) that will help you to reduce syntactic error.
public void dataAccess(){
try {
String connectionUrl = "suitable connection url as per your database";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
Class.forName("JDBC driver name as per your database");
con = DriverManager.getConnection(connectionUrl, userName, password);
String SQL = "SQL query as per your criteria";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
// look into ResultSet api and use method as per your requirement
}
rs.close();
}
catch (Exception e) {
//log error message ;
}
}

How to start Derby server on the specified port by java

I tried to test Derby sample source code. Unfortunately it failed: Cannot connect Derby database: connection refused
I was told that I haven't started a server. Official tutorial:
Doesn't start any server.I have no feedback after C:\Apache\db-derby-10.4.1.3-bin\lib> java -jar derbyrun.jar server start just empty line shows and the derbyrun.jar ends.
Doesn't show how to create server on the specified port
My question is: How to start a server on the specified port so the posted code works:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
public class Restaurants
{
private static String dbURL = "jdbc:derby://localhost:1526/myDB;create=true;user=me;password=mine";
private static String tableName = "restaurants";
// jdbc Connection
private static Connection conn = null;
private static Statement stmt = null;
public static void main(String[] args)
{
createConnection();
insertRestaurants(5, "LaVals", "Berkeley");
selectRestaurants();
shutdown();
}
private static void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
}
catch (Exception except)
{
except.printStackTrace();
}
}
private static void insertRestaurants(int id, String restName, String cityName)
{
try
{
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (" +
id + ",'" + restName + "','" + cityName +"')");
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void selectRestaurants()
{
try
{
stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("select * from " + tableName);
ResultSetMetaData rsmd = results.getMetaData();
int numberCols = rsmd.getColumnCount();
for (int i=1; i<=numberCols; i++)
{
//print Column Names
System.out.print(rsmd.getColumnLabel(i)+"\t\t");
}
System.out.println("\n-------------------------------------------------");
while(results.next())
{
int id = results.getInt(1);
String restName = results.getString(2);
String cityName = results.getString(3);
System.out.println(id + "\t\t" + restName + "\t\t" + cityName);
}
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void shutdown()
{
try
{
if (stmt != null)
{
stmt.close();
}
if (conn != null)
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
}
}
catch (SQLException sqlExcept)
{
}
}
}
Setting port numbers
By default, Derby using the Network Server listens on TCP/IP port number 1527. If you want to use a different port number, you can specify it on the command line when starting the Network Server. For example:
java org.apache.derby.drda.NetworkServerControl start -p 1088
However, it is better to specify the port numbers by using any of the following methods
1. Change the startNetworkServer.bat or startNetworkServer.ksh scripts
2. Use the derby.drda.portNumber property in derby.properties
Please refer to:
https://db.apache.org/derby/docs/10.5/adminguide/tadminappssettingportnumbers.html

Resultset handling error in servlet code

I write a code in servlet for login checking I don't know why I get an error like java.sql.SQLException: No data found, if I had not commented out the String s4 = rs.getString(1) and out.println(s4) line if I commented out this lines I did not get any error.
Why do I get an error like this? I cannot find out the answer.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class login extends HttpServlet {
Connection conn;
Statement stmt;
ResultSet rs;
String s = "";
public void init() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("Jdbc:Odbc:edsn");
s = "Your information is connected ......";
} catch (Exception e) {
s = "Exception 1....." + e.getMessage();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
out.println(s);
try {
String ID = req.getParameter("T1");
String query = "select * from user_db ";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
out.println("user" + " " + "pass");
while (rs.next()) {
try {
if ((rs.getString(1)).equals(ID)) {
String s4 = rs.getString(1);
out.println(s4);
out.println("<html><body><h> login Pass.....:(</h></body></html>");
}
} catch (Exception e) {
out.println(e);
}
}
} catch (Exception e) {
out.println("Unable To Show the info... . . ." + e.getMessage());
}
}
}
Why write the code like this ? It's very wasteful going over the whole table...
The IO alone...
Why not change to this:
ResultSet rs = null;
PreparedStatement st = null;
try {...
String ID = req.getParameter("T1");
String query = "select 1 from user_db where col_name = ?";
st = conn.prepareStatement(query);
st.setString(1, ID);
rs = st.executeQuery();
if (rs.next()) {
out.println(ID);
out.println("<html><body><h> login Pass.....:(</h></body></html>");
}
..
} finally {
if (rs != null) try { rs.close();}catch (Exception e) {}
if (st != null) try { st.close();}catch (Exception e) {}
}
notice prepared statements are cached and better for frequent use
you let the db do what its good at - search the data
select 1 instead of select * does not bring back data you dont really need
jdbc works harder the more columns and data in general you return, so only get what you
need
and add a finally block to always close your db connections properly
Calling methods on Connection, Statement, or ResultSet depend on which JDBC driver you've loaded. All the values of the ResultSet could be set as soon as the query is made, or they could be retrieved from the database as they're needed, depending on the implementation of the driver.
The JdbcOdbcDriver throws an SQLException after calling getString for a second time. This can be worked around be storing the values in Strings instead of making multiple calls, or by switching to a different driver.

How to check for mysql errors in java

I'm trying to do a simple insert query in mysql using java. How do I determine what the problem is if its not doing what its supposed to do:
import java.util.*;
import java.sql.*;
import javax.swing.JOptionPane;
public class regp {
public regp(String player, int score) {
conc conclass = new conc();
Connection conn = conclass.dbConnect();
try {
PreparedStatement fetchPlayers = conn.prepareStatement("SELECT * FROM players WHERE P_Name='" + player + "'");
ResultSet rs = fetchPlayers.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Already Registered!");
} else {
PreparedStatement createPlayer = conn.prepareStatement("INSERT INTO players(P_Name, Score) VALUES('" + player + "', '" + score + "')");
createPlayer.execute();
JOptionPane.showMessageDialog(null, "Player: " + player + " score: " + score);
JOptionPane.showMessageDialog(null, "Registration Successful!");
JOptionPane.showMessageDialog(null, "Not registered!");
}
} catch (Exception e) {
}
}
}
And heres conc.java which contains the database information:
import java.sql.*;
import java.util.*;
public class conc {
public conc(){
}
public Connection dbConnect() {
try {
String db_connect_string="jdbc:mysql://localhost:3306/questions";
String db_userid="root";
String db_password="1234";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Problem is I don't have any idea if its the query, the prepared statement declaration.
One thing is sure to be working. The part which checks if the player inputted is existing or not.
I already checked if the function is getting the values needed by outputting them using joptionpane message dialog. And it sure receives the correct values. So I'm thinking that maybe the problem is in the query.
You could print the exception that you're catching in your regp constructor:
} catch (Exception e) {
e.printStackTrace();
}
You may also want to look at prepared statements rather than constructing your SQL via string concatenation.

Categories