How to check for mysql errors in java - 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.

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

Why doesn't my Java code create a table in an in-memory SQLite database and print the table name?

I want to create an in-memory database and check that the table exists afterwards. Unfortunately, my code doesn't print anything to the console, so either the check for a table or the table creation process is wrong.
How do I fix it?
import java.sql.*;
public class Main {
private static String url = "jdbc:sqlite::memory";
private static void createNewTable(Connection conn) {
String sql = "CREATE TABLE IF NOT EXISTS students (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text NOT NULL"
+ ");";
try (Statement stmt = conn.createStatement();) {
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void checkTable(Connection conn){
String sql = "SELECT name FROM sqlite_temp_master WHERE type='table'";
try (Statement stmt = conn.createStatement();) {
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("table: " + rs.getString(1));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
Connection conn;
try{
conn = DriverManager.getConnection(url);
createNewTable(conn);
checkTable(conn);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}

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

Categories