How to start Derby server on the specified port by java - 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

Related

Access is Denied, Issue in embedded Derby

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

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");
}

Inserting data into a database - org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:

I've been trying to save values into a database called "CLIENT".
The database is created via this code:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleCreateTables {
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main (String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE CLIENT " +
"(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
" fullNames VARCHAR(255), " +
" iDNumber VARCHAR(255), " +
" pINNumber VARCHAR(255), " +
" passportNumber VARCHAR(255), " +
" postOfficeBoxNumber VARCHAR(255), " +
" postalCode VARCHAR(255), " +
" telephoneNumberLandline VARCHAR(255), " +
" telephoneNumberMobile VARCHAR(255), " +
" CARD VARCHAR(255)) ";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt!=null)
conn.close();
} catch(SQLException se) {
} // do nothing
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
} // end main
} // end
The class that I'm trying to have save into the database is:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleInsertRecords {
public final String values;
public final String table;
public JDBCExampleInsertRecords (String values, String table)
{
this.values = values;
this.table = table;
}
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main () {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(getJDBC_DRIVER());
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
} // do nothing
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
System.out.println("Goodbye!");
} //end main
/**
* #return the JDBC_DRIVER
*/
public static String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
/**
* #param aJDBC_DRIVER the JDBC_DRIVER to set
*/
public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
JDBC_DRIVER = aJDBC_DRIVER;
}
/**
* #return the DB_URL
*/
public static String getDB_URL() {
return DB_URL;
}
/**
* #param aDB_URL the DB_URL to set
*/
public static void setDB_URL(String aDB_URL) {
DB_URL = aDB_URL;
}
/**
* #return the USER
*/
public static String getUSER() {
return USER;
}
/**
* #param aUSER the USER to set
*/
public static void setUSER(String aUSER) {
USER = aUSER;
}
/**
* #return the PASS
*/
public static String getPASS() {
return PASS;
}
/**
* #param aPASS the PASS to set
*/
public static void setPASS(String aPASS) {
PASS = aPASS;
}
} //end
The code that gets the values is in a Class called "AddNewClient" and is as follows:
public String getValues () {
String fullNames = fullNamesJTextField.getText();
String iDNumber = identificationNumberJTextField.getText();
String pINNumber = pINNumberJTextField.getText();
String passportNumber = passportNumberJTextField.getText();
String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
String postalCode = postalCodeJTextField.getText();
String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();
List<String> client = new ArrayList<String>();
client.add(fullNames);
client.add(iDNumber);
client.add(pINNumber);
client.add(passportNumber);
client.add(postOfficeBoxNumber);
client.add(postalCode);
client.add(telephoneNumberLandline);
client.add(telephoneNumberMobile);
StringBuilder builder = new StringBuilder();
String listStringClient = "";
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
return listStringClient;
}
I get an error message:
run:
Connecting to a selected database...
Connected database successfully...
Inserting records into the table...
org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:
I've been at this for the past two days to no success whatsoever. I will be very, very very greatful to anyone who would come to my rescue. Thank you.
This is where one problem is:
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
stmt.executeUpdate(sql);
Values should be the getValues() method, instead of just a string, so
String sql = "INSERT INTO CLIENT VALUES (" + getValues() + ")";
Additionally, since you do not specify which columns, it is assumed that all columns are being entered in the values. If CARD does not have a default value in your SQL database, and if it cannot be NULL, you're going to have a problem.
Finally, this is a little strange:
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
You'll want the values, not 'NULL', so it should be
for (String s : client)
{
listStringClient += "'" + s + "'" + ",";
}
And finally, the way you're doing it, you're going to have an extra comma at the end (ex: 'value1','value2','value3',)
Clip the final comma:
return listStringClient.substring(0, listStringClient.size() - 1);
Granted, there's a better way to do the for loop where you do not have that extra comma.
End the end, the sql String should look like this:
"INSERT INTO CLIENT VALUES('value1','value2','value3','value4','value5','value6')"
Do a System.out.println(sql) and see what the String statement is that you're trying to execute. You'll see the error then.
Here's a better way to build your values string without the comma issue:
Iterator<String> iter = client.iterator();
StringBuilder sb = new StringBuilder();
while (iter.hasNext()) {
sb.append("'").append(iter.next()).append("'");
if (iter.hasNext())
sb.append(",");
}
return sb.toString();
You forget to mention the value for CARD column. If you dont want to set any value there, just pass ' '.
Your for loop should be like this
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";//GIVES YOU ERROR BECAUSE AT THE END OF
} // FOR LOOP IT HAS , IN THE END OF STRING.
listStringClient+="' '";//This is for CARD COLUMN.
You do not pass any value in your statement. Following code is static, it does not have parameters:
INSERT INTO CLIENT " + "VALUES ((values))
It is nonsense SQL command: INSERT INTO CLIENT VALUES ((values)). You wanted express
String sql = "INSERT INTO CLIENT VALUES " + getValues()";
I prefer to use PreparedStatement, as it is safe and it will escape dangerous characters:
String sql = "INSERT INTO PRODUCT VALUES(?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, "asdf");
prest.setInt(2, 2009);
// etc
int count = prest.executeUpdate();
I think instead of :
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
You want something like :
String sql = "INSERT INTO CLIENT " + "VALUES ("+getValues()+")";
Also the implementation of getValues is kind of strange :
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
Probably it could be :
for (String s : client)
{
listStringClient += "'" + s + "',"
}
listStringClient += "NULL";
I can't thank you all enough for the amazing answers. I put the various ideas and came up with this solution to my problem.
My working answer to my Question above takes ideas from Leos Literak, abmitchell, Vimal Bera and Grisha's answers.
The database is created via this code:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleCreateTables {
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main (String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE CLIENT " +
"(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
" fullNames VARCHAR(255), " +
" iDNumber VARCHAR(255), " +
" pINNumber VARCHAR(255), " +
" passportNumber VARCHAR(255), " +
" postOfficeBoxNumber VARCHAR(255), " +
" postalCode VARCHAR(255), " +
" telephoneNumberLandline VARCHAR(255), " +
" telephoneNumberMobile VARCHAR(255)) ";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt!=null)
conn.close();
} catch(SQLException se) {
} // do nothing
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
} // end main
} // end
The class that saves into the database is:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleInsertRecords {
public static String values;
public final String table;
public JDBCExampleInsertRecords (String values, String table)
{
this.values = values;
this.table = table;
}
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main () {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(getJDBC_DRIVER());
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO CLIENT VALUES (NULL, " + (values) + ")";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
} // do nothing
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
System.out.println("Goodbye!");
} //end main
/**
* #return the JDBC_DRIVER
*/
public static String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
/**
* #param aJDBC_DRIVER the JDBC_DRIVER to set
*/
public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
JDBC_DRIVER = aJDBC_DRIVER;
}
/**
* #return the DB_URL
*/
public static String getDB_URL() {
return DB_URL;
}
/**
* #param aDB_URL the DB_URL to set
*/
public static void setDB_URL(String aDB_URL) {
DB_URL = aDB_URL;
}
/**
* #return the USER
*/
public static String getUSER() {
return USER;
}
/**
* #param aUSER the USER to set
*/
public static void setUSER(String aUSER) {
USER = aUSER;
}
/**
* #return the PASS
*/
public static String getPASS() {
return PASS;
}
/**
* #param aPASS the PASS to set
*/
public static void setPASS(String aPASS) {
PASS = aPASS;
}
} //end
The code that gets the values is in a Class called "AddNewClient" and is as follows:
public String getValues () {
String fullNames = fullNamesJTextField.getText();
String iDNumber = identificationNumberJTextField.getText();
String pINNumber = pINNumberJTextField.getText();
String passportNumber = passportNumberJTextField.getText();
String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
String postalCode = postalCodeJTextField.getText();
String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();
List<String> client = new ArrayList<String>();
client.add(fullNames);
client.add(iDNumber);
client.add(pINNumber);
client.add(passportNumber);
client.add(postOfficeBoxNumber);
client.add(postalCode);
client.add(telephoneNumberLandline);
client.add(telephoneNumberMobile);
Iterator<String> iter = client.iterator();
StringBuilder sb = new StringBuilder();
while (iter.hasNext()) {
sb.append("'").append(iter.next()).append("'");
if (iter.hasNext())
sb.append(",");
}
return sb.toString();
}

Querying a database via a constructor

I'm really hopping some help from anyone who would be kind enough to help me resolve this. I've been at it since yesterday.
See, what I'm trying to do is create a database query class that I can re-use over and over again as many times as possible without having to write a query every other time I need to search or display items from the database.
I'd like to be able to pass the query specifications via a constructor.
I however, get this error:
run:
Connecting to a selected database...
Connected database successfully...
Creating statement...
org.h2.jdbc.JdbcSQLException: Data conversion error converting ; SQL statement:
This is my code so far:
import java.sql.*;
public class RsToAList {
private final String table;
private final String columns;
private final String whereColumn;
private final String equalsEntry;
public RsToAList (String columns, String table, String whereColumn, String equalsEntry) {
this.table = table;
this.columns = columns;
this.whereColumn = whereColumn;
this.equalsEntry = equalsEntry;
}
// JDBC driver name and database URL
static String JDBC_DRIVER = "org.h2.Driver";
static String DB_URL = "jdbc:h2:file:C:/tryDb/tryDb";
// Database credentials
static String USER = "sa";
static String PASS = "";
public static void main (String[] args) {
RsToAList tryAndGet = new RsToAList("fullNames", "CLIENT", "postOfficeBoxNumber", "6448");
tryAndGet.ourQueryMethod();
}
public void ourQueryMethod () {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(getJDBC_DRIVER());
// STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
System.out.println("Connected database successfully...");
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" = "+ (equalsEntry) +"";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String first = rs.getString(columns);
// Display values
System.out.print("ID: " + first);
}
rs.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
} // do nothing
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
} // end main
/**
* #return the JDBC_DRIVER
*/
public static String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
/**
* #param aJDBC_DRIVER the JDBC_DRIVER to set
*/
public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
JDBC_DRIVER = aJDBC_DRIVER;
}
/**
* #return the DB_URL
*/
public static String getDB_URL() {
return DB_URL;
}
/**
* #param aDB_URL the DB_URL to set
*/
public static void setDB_URL(String aDB_URL) {
DB_URL = aDB_URL;
}
/**
* #return the USER
*/
public static String getUSER() {
return USER;
}
/**
* #param aUSER the USER to set
*/
public static void setUSER(String aUSER) {
USER = aUSER;
}
/**
* #return the PASS
*/
public static String getPASS() {
return PASS;
}
/**
* #param aPASS the PASS to set
*/
public static void setPASS(String aPASS) {
PASS = aPASS;
}
}
I'm a JAVA/ Programming newbie, and I'm trying to teach myself how to code from home in case my question seems too simple, or I seem to have overlooked something in my code.
Edit:
I'm not sure if this could help you help me, but this is the class that creates the database table:
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleCreateTables {
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/tryDb/tryDb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main (String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE CLIENT " +
"(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
" fullNames VARCHAR(255), " +
" iDNumber VARCHAR(255), " +
" pINNumber VARCHAR(255), " +
" passportNumber VARCHAR(255), " +
" postOfficeBoxNumber VARCHAR(255), " +
" postalCode VARCHAR(255), " +
" telephoneNumberLandline VARCHAR(255), " +
" telephoneNumberMobile VARCHAR(255)) ";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt!=null)
conn.close();
} catch(SQLException se) {
} // do nothing
try {
if (conn!=null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
System.out.println("Goodbye!");
} // end main
} // end
Looks like a error in your sql statement.Make sure the data type you are comparing is compatible.PreparedStatement is handy instead of concatenating queries.
PreparedStatement stm = conn.prepareStatement("select * from person where name=?");
stm.setString(1,"ABC");
ResultSet rs= stm.executeQuery();
Although you have not shared the column type for the where condition. But most proabably you may be passing a string value to where clause but not enclosing it in single quotes:
String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" = "+ (equalsEntry) +"";
change it to:
String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" ='"+ (equalsEntry) +"'";
The other potential candidate for defect is this statementn:
String first = rs.getString(columns);
It may throw an error if any of your column type is not VARCHAR

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