How to retrieve elements from a database into a JDBC program - java

I tried a basic program to retrieve data from a database table into a java program. At the end of the compilation, when running the code an exception occurs. No error is shown in the console. It displays the exception message
import java.sql.*;
public class class1 {
public static void main(String args[]){
String url = "jdbc:mysql://localhost:3306//orders";
String username = "root";
String password = "Luxan#22";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, username, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT CUST_NAME FROM CUSTOMERS");
System.out.println("List of Registered customers: ");
while(rs.next()){
System.out.println(rs.getString("cust_name"));
}
st.close();
con.close();
}
catch(Exception e){
System.out.println("An Exception error occured while processing JDBC programme");
}
}
}
Below is the output got in my console window
Fri Jan 17 19:34:24 IST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
An Exception error occured while processing JDBC programme

The problem is with your URL. Replace
"jdbc:mysql://localhost:3306//orders"
with
"jdbc:mysql://localhost:3306/orders"
Note that I have removed one / before orders.

Try to add ?useSSL=false to the end of the connection url.

It is difficult to see what went wrong, without knowing your table structure. But here is another way of writing your program. Maybe it helps you come closer to your goal:
public class Class1 {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver"); // this line is optional since Java 1.6 Normally for MySQL you shouldn't have to do this
// This is called "try-with-resources". It means that inside your "try" declaration you
// tell Java what things you want to open (here you wnat to open a connection)
// and it will automatically close any connection (on failure or success) for you
try (
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", // before the database name there is only one /
"root", // the database user
"password"); // the password
Statement statement = connection.createStatement() // the same try-with resources can open the statement for your
) {
ResultSet rs = statement.executeQuery("SELECT CUST_NAME FROM CUSTOMERS");
while (rs.next()) {
System.out.println(rs.getString("cust_name"));
}
} catch (SQLException ex) {
Logger.getLogger(Class1.class).log(Level.SEVERE, null, ex); // this will properly log your SQLException. Don't be afraid, SQL error messages are scary and Java Exceptions are impressive. But they will tell you where the problem is
}
} catch (ClassNotFoundException ex) { // if you register your driver you need to catch the exception as well
Logger.getLogger(Class1.class).log(Level.SEVERE, null, ex);
}
}
}
You can read more about this example on MkYong.
I hope it helps you.
One more thing:
Class names start with a capital letter: Class1 instead of class1. Because variable names start with a small letter. Imagine you want to create an instance of a class called car. Then you would say car car = new car(); which is unreadable. Car car = new Car() however is clear :)

Related

Try-catch ignoring the assignment of a variable when executing an SQL query

This piece of code uses an SQL query to return how many entries there are in a certain table.
public int countAmountOfEntries() {
int amount;
try (Connection conn = DriverManager.getConnection(Connection.JDBC_URL);
PreparedStatement query = conn.prepareStatement("SELECT COUNT(*) FROM Table")) {
try (ResultSet rs = query.executeQuery();) {
if (rs.next()) {
amount = rs.getInt("COUNT(*)");
}
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
return amount;
}
This should return any int other than 0. Initialising the variable to 0 will result in a NullPointerException being thrown as I'm using the return value of this to set the length of an array. Using the same code in another class returns the int it should return. I've tried using an alias for the COUNT(*) but to no avail.
Running the query directly into MySQL returns the int as well. I've tried removing the nested try (it was pretty much obsolete since I know it won't throw an exception if no one messes with my DB).
Did you register the JDBC driver before using it?
Class.forName("com.mysql.jdbc.Driver");
Is it required to provide an username/password upon connecting?
DriverManager.getConnection(url, user, pass);
Did you create a Connection class yourself which overwrites the Connection class returned upon opening the connection. The reason I ask this is because you retrieve the URL to connect to using Connection.JDBC_URL which is (as far as I know) not in the Connection class.
Is there already a connection opened and your database only allows 1 open connection?
Note: do not forget to close the resultset, statement, and connection before returning:
rs.close();
query.close();
conn.close();
Besides that, restructure your function because a try without catch does not help at all.
This looks really weird:
amount = rs.getInt("COUNT(*)");
Try this instead
amount = rs.getInt(1);

The driver was unable to create a connection to mysql

I'm programming in java SE and I get an error when trying to access to create a connection to mysql. I can connect to mysql, in fact, the error shows up when running a bucle.
What I do in this program is to check for a String in the table Colors of my database and if it finds nothing it creates this String in the table with an autoincrementing id.
It works fine, but after having checked it for a while it gives me the error.
I attach the image of the error and the code where I create the connection.
public Integer codiColor(String col){
Integer codi=null;
if(col.equals(""))
return 1;
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url, usuari, password);//here is the error
try {
Statement st = con.createStatement();
String sql = "SELECT CODICOL FROM COLORES where COLOR ='"+col+"'";
ResultSet res = st.executeQuery(sql);
if(res.next()){
codi = res.getInt("CODICOL");
}
try { res.close(); } catch (Exception e) {}
try { st.close(); } catch (Exception e) {}
}
catch(SQLException s){
JOptionPane.showMessageDialog(null, "Error:\n"+s.getMessage(),
"ERROR.",JOptionPane.ERROR_MESSAGE);
}
finally{
try { con.close(); } catch (Exception e) {}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return codi;
}
This code is the one that checks if the color already exists or not.
EDIT:
url = "jdbc:mysql://192.168.1.200:3306/mybbdd?zeroDateTimeBehavior=convertToNull";
The problem is that con is evidently a member variable where it should be a local variable. If this piece of code and others like it are called from multiple threads, a con value will be overwritten and therefore lost, so a connection leak will result. You will almost certainly also have other problems due to concurrent use of the connection. Make it a local variable.
NB you haven't needed the Class.forName() line since 2007. The close of the connection, statement, and result set would be redundant if you used try-with-resources. And you should use a prepared statement.
String sql = "SELECT CODICOL FROM COLORES where COLOR =?";
try (con = DriverManager.getConnection(url, usuari, password);
PreparedStatement st = con.prepareStatement(sql);
) {
st.setObject(1, col);
ResultSet res = st.executeQuery();
if(res.next()){
codi = res.getInt("CODICOL");
}
}
catch(SQLException s){
JOptionPane.showMessageDialog(null, "Error:\n"+s.getMessage(),
"ERROR.",JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
I find the way out. I googled the number the java error gave to me and I found that adding a registry key to be able to do more connections should work.
I first did it on the server, to allow more connections from clients but it didn't still work so I tried to do it on my computer and for now it works.
This is the link from microsoft
In your code you giving a new connection on every call but you need to understand your OS allows you Only Limited Connection.
after cross Limit it will Not allow you to make another Connection.
i don't know what's your requirement but if you really need Connection
So better option is that you need to make Connection Pool. If user required a connection to do some task then user can Take Connection from connection Pool and after Work Finished user can return that connection to connection pool.
For Achieve this you need to Design Your Configuration File Or you need Design interface library interface and implement according to your Requirement.

Connecting to database with JDBC URL

My requirement is to check can we connect to a database with no schema defined through a java program and create a database.
this works fine
Connection connection =
DriverManager.getConnection("jdbc:db2://wcspocca-db.cloudapp.net:50001/db2inst1","vmadmin","password#123;");
database: db2
schema: db2inst1
but
Connection connection =
DriverManager.getConnection("jdbc:db2://wcspocca-db.cloudapp.net:50001/","vmadmin","password#123;");
fails
WHY?
com.ibm.db2.jcc.am.mo: [jcc][10165][10045][4.7.85] Invalid database URL syntax: jdbc:db2://wcspocca-db.cloudapp.net:50001/. ERRORCODE=-4461, SQLSTATE=42815
DriverManager.getConnection("jdbc:db2://wcspocca-db.cloudapp.net:50001/!!DBNAME!!","vmadmin","password#123;");
How I usually connect to a database using jave is like the following: Spacing it out to allow you to read the text below
//Wide Scope Variables
static Connection conn = null; //right now this connection is off
static String dbURL = "database url"; //I use SQL developer and your able to grab the connection url there
static String user = "This can be empty and ask user for input of hard code the user name";
static String pass = "same as above";
In the method where you want to check the driver and connection I usually do it like this
//Register the Driver
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e)
{
System.err.println(e.getMessage());
}
//Set up connection
try
{
conn = DriverManager.getConnection(dbURL,user,password);
conn.clearWarnings();
stmt = conn.createStatement();
}
catch(SQLException e)
{
System.err.println(e.getMessage());
}
The first try catch code registers the driver to the SQL developer then the second try catch sets up the connection to the database. This helped save me a lot of head aches and I find it the most Direct route when using java.
Because in the second example the database is not specified. You can find the requirements in the DB2 JDBC documentation:
>>-+-jdbc:db2:------+--//--server--+---------+--/--database----->
+-jdbc:db2j:net:-+ '-:--port-'
'-jdbc:ids:------'
>--+---------------------------+-------------------------------\><
'-:--| connection-options |-'
The database parameter is not optional.
check the url carefully, after the port number if you do not put database name which you want to connect then how it will connect. Its like you are giving a home address whitout the plot number.

Custom database table design with Java and MS Access

While running the following code
public class Temp {
public static void main(String args[]) {
Connection con; // The connection to the database.
// The following code can throw errors, so they must be caught.
try{
// First, tell Java what driver to use and where to find it.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Next, create a connection to your data source.
// Specify that you are using the ODBC-JDBC Bridge.
// And specify the data source from ODBC.
con = DriverManager.getConnection("jdbc:odbc:Temp");
// Create an SQL statement.
Statement stmt = con.createStatement();
// Execute some SQL to create a table in your database.
// If the table already exists, an exception is thrown!
stmt.executeUpdate("CREATE TABLE COFFEES " +
"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)");
}
// Catch any exceptions that are thrown.
catch(ClassNotFoundException e){
System.out.println(e.toString());
}
catch(SQLException e){
System.out.println(e.toString());
}
}
}
i got the error as
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Cannot modify the design of table 'COFFEES'. It is in a read-only database.
please help
Make sure that you have write access to the database/file with your current user.
Check the advanced options in the ODBC DSN and make sure ReadOnly is set to 0.
You need to add "ReadOnly=False;" to your connection string
try deleting the table explicitly and run again.

JDBC MYSQL Connection without specifying database?

I am using the SphinxQL MySQL client which stores indexes as "tables" but has no real notion of a "database"...One specifies the port (9306 in my case) at which the sphinx mysql instance listens and in theory should be able to communicate as normal.
I have the following test code:
import java.sql.*;
public class Dbtest {
public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:9306",
"user","password");
con.setReadOnly(true);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * from index_turned_table");
while (res.next()) {
String stuff1 = res.getString(1);
String stuff2 = res.getString(2);
System.out.println("Adding " + stuff1);
System.out.println("Adding " + stuff2);
}
res.close();
stmt.close();
con.close();
}
catch(Exception e)
{
System.out.println (e);
}
}
Upon execution, the code just hangs and does nothing and doesn't print out an exception. What are useful things I can do to figure this out or if any one has direct experience what might be going on?
This work with 1.10-beta http://www.olegsmith.com/2010/12/scalalift-sphinxql.html
and not work with 2.0.1-beta. Use mysql-connector-java 5.1.15.
Your SphinxQL instance is listening on port 9306. Your MySQL is listening on some other port, likely on the default 3306. You can use MySQL JDBC driver to connect to MySQL, but you cannot use it to connect to SphinxQL. It just doesn't understand JDBC driver communication protocol.

Categories