I'm creating my first Java program that pulls data from a MySql database. I'm having trouble getting the result from a query to print in console. My program compiles without error but out.print command not displaying content in console. I'm using Intellij IDEA 15.0.2.
import java.sql.*;
import static java.lang.System.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/animal";
String user = "username";
String pwd = "password";
try {
Connection connection =
DriverManager.getConnection(url, user, pwd); // Get Connection
Statement statement = connection.createStatement(); // Create Statement
String query = "SELECT * FROM animal";
ResultSet resultSet = statement.executeQuery(query); // Execute Query
while (resultSet.next()) { // Process Results
out.print(resultSet.getInt("animal_id"));
}
} catch (SQLException se) { }
}
}
To print out to console the correct command is
System.out.print("Whatever you want to print");
not
out.print("Whatever you want to print");
Yeah.. as BradStell said you have to use
System.out.print(resultSet.getInt("animal_id"));
instead of
out.print(resultSet.getInt("animal_id"));
Another suggestion that I would like to make is Always do something on catching an exception. You have no code in the catch block. Atleast try to print the exception there. That would help you very much in finding errors in your code .
The problem was with the database driver. I needed to use the forName method(), and add the driver url for MySql. After I successfully implemented this class I was able to create sql queries without issue. Thanks for the tip with the exception handling #Senthil Vidhiyakar
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.print("Working");
}
catch (Exception e){ System.out.println("Not working");}
I also had to connect the mysql connector jar. The process for doing this in Intellij IDEA is as follows.
File >> Project Structure "The project structure window will appear then on the left side menu click Modules in the main content area click on the Dependencies tab. Next click the green +. Choose option 1 JARs or directories. Finally, navigate to the mysql connector jar. Then click apply, and ok."
Related
I am building a java app that gets data from the file system (parquet) in mapR cluster. I was initially using apache spark but the processing was quite slow.
So i decided to use the drill jdbc connection approach.
Following the documentation in mapR https://mapr.com/docs/52/Drill/Using-JDBC-Driver-App.html
Here is my code
Step 1;
placed the driver jar in a lib folder in my project path as shown;
[project directory][1]
[1]: https://i.stack.imgur.com/APsZi.png
step 2;
Imported the jar to my maven pom.xml
<dependency>
<groupId>DrillJDBC41</groupId>
<artifactId>DrillJDBC41</artifactId>
<scope>system</scope>
<version>1.0</version>
<systemPath>${project.basedir}\src\lib\DrillJDBC41.jar</systemPath>
</dependency>
step 3
my code implementation
try {
private static final String CONNECTION_URL = "jdbc:drill:zk=192.168.1.1:31010/drill/dev.maprcluster.com-drillbits;schema=dfs";
private static final String JDBC_DRIVER = "com.mapr.drill.jdbc41.Driver";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
// Define a plain query
String query = "SELECT * FROM `dfs.default`.`/storage/products/data/d/report/2019/07/12`" + " where unique_key = '00209220' LIMIT 30";
// Register the driver using the class name
Class.forName(JDBC_DRIVER);
// Establish a connection using the connection
// URL
try {
System.out.println("about establishing connection");
con = DriverManager.getConnection(CONNECTION_URL);
System.out.println("connection established");
}catch (Exception e){
System.out.println("EXCEPTION OO");
e.printStackTrace();
}
// Create a Statement object for sending SQL
// statements to the database
stmt = con.createStatement();
System.out.println("trying to execute query");
// Execute the SQL statement
rs = stmt.executeQuery(query);
// Display a header line for output appearing in
// the Console View
System.out.println("gotten result set");
// Step through each row in the result set
// returned from the database
while(rs.next()) {
// Retrieve values from the row where the
System.out.println("data is returned");
// cursor is currently positioned using
// column names
// Display values in columns 20 characters
// wide in the Console View using the
// Formatter
}
} catch (SQLException se) {
System.out.println("sql exception");
se.printStackTrace();
// Handle errors encountered during interaction
// with the data source
} catch (Exception e) {
e.printStackTrace();
// Handle other errors
} finally {
// Perform clean up
try {
System.out.println("entered finally block");
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException se1) {
se1.printStackTrace();
}
} // End try
}
PROBLEM
The application builds fine but when i try to get data , it stops after printing this;
about establishing connection
and goes straight into the finally block without throwing any exception.
I am not sure what the problem is.
I also tried another another implementation using apache drill
<dependency>
<groupId>org.apache.drill.exec</groupId>
<artifactId>drill-jdbc-all</artifactId>
<version>1.1.0</version>
</dependency>
changed the driver to this;
private static final String JDBC_DRIVER_DRILL = "org.apache.drill.jdbc.Driver";
still the same problem.
No error thrown.
Output;
about establishing connection
entered finally block
UPDATE
I caught Throwable as advised and i was getting the following error;
java.lang.NoSuchMethodError: com.google.common.base.Stopwatch.createStarted()Lcom/google/common/base/Stopwatch;
at org.apache.drill.common.config.DrillConfig.create(DrillConfig.java:189)
at org.apache.drill.common.config.DrillConfig.create(DrillConfig.java:163)
at org.apache.drill.common.config.DrillConfig.forClient(DrillConfig.java:114)
at com.mapr.drill.drill.client.DRJDBCClient.openSession(Unknown Source)
at com.mapr.drill.drill.client.DRJDBCClient.<init>(Unknown Source)
at com.mapr.drill.drill.core.DRJDBCConnection.connect(Unknown Source)
at com.mapr.drill.jdbc.common.BaseConnectionFactory.doConnect(Unknown Source)
at com.mapr.drill.jdbc.common.AbstractDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
Looking at this line,
`private static final String CONNECTION_URL = "jdbc:drill:zk=192.168.1.1:31010/drill/dev.maprcluster.com-drillbits;schema=dfs";`
The documentation you provided a link to, stated it to be an example of connecting to a zookeeper cluster. And you copied the same server address provided in the example. There are many cluster managers like Yarn and Mesos. Ensure you are using the correct connection string to the right manager in your cluster and again, the server addresses should correspond to the respective addresses in your cluster.
Again, separate the aspect of the code that you want to use to get connection to a separate class and handle the logic in a single try-catch block, for the sake of separation of concern, instead of having it in a nested try-catch block in your service class.
This would enable you to test and debug more easily to understand what is happening.
Finally, since there's no static trace to inform of the error, the right approach is to debug the connection class (assuming you have extracted it out), then step through it to learn what is happening in that line. That would enable you to figure out what to do next.
I love Apache Drill, but is this really the best way to read Parquet data if you are worried about speed?
The AvroParquetReader might be a better approach for directly reading a Parquet-formatted file.
You can also use the ParquetFileReader class directly. Example here:
https://www.jofre.de/?p=1459
and here:
https://www.arm64.ca/post/reading-parquet-files-java/
I've tried most of the examples found here and the web, but I can't open a MS access database(2002 or 2013) and get an updatable result set using UCanAccess. The same code using the JDBC:ODBC driver/connection/works. I've written short test code to check concur_updatable to check this, so I must be missing something. I'm using JDK 1.7 on a Win7 machine. I also have another machine with the same results.
This works:
/*
class jdbc, for testing jdbc:odbc CONCUR_UPDATABLE.
*/
import java.sql.*;
public class jdbc {
private static String dbFQN;
public static void main(String[] args) {
try {
dbFQN = ("C:\\phil\\programming\\kpjl2002.mdb");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbFQN;
System.out.println("Loading database: " + database);
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
// Fetch records from table
String selTable = "SELECT * FROM " + "tblLibrary" + " ORDER BY Artist, Cat, Cart";
s.execute(selTable);
ResultSet rs = s.getResultSet();
int concurrency = rs.getConcurrency();
if(concurrency == ResultSet.CONCUR_UPDATABLE)
{
System.out.println("rs is updatable");
} else {
System.out.println("rs Not updatable");
}
s.close();
conn.close();
} //close try
catch (Exception ex) {
ex.printStackTrace();
} //close catch
} //close main method
} //close dbAccess class
The output is that rs is updatable.
This doesn't work:
/*
class ucan, for testing ucanaccess CONCUR_UPDATABLE.
C:\jdk1.7.0_79\jre\lib\ext\ucanaccess-2.0.9.5.jar
C:\jdk1.7.0_79\jre\lib\ext\hsqldb.jar
C:\jdk1.7.0_79\jre\lib\ext\jackcess-2.1.0.jar
C:\jdk1.7.0_79\jre\lib\ext\commons-lang-2.6.jar
C:\jdk1.7.0_79\jre\lib\ext\commons-logging-1.1.1.jar
also present:
C:\jdk1.7.0_79\jre\lib\ext\commons-logging-1.2.jar
C:\jdk1.7.0_79\jre\lib\ext\commons-lang3-3.4.jar
*/
import java.sql.*;
public class ucan {
private static String dbFQN;
public static void main(String[] args) {
try {
dbFQN = ("C:\\phil\\programming\\kpjl2002.mdb");
String database = "jdbc:ucanaccess://" + dbFQN;
System.out.println("Loading database: " + database);
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
// Fetch records from table
String selTable = "SELECT * FROM " + "tblLibrary" + " ORDER BY Artist, Cat, Cart";
s.execute(selTable);
ResultSet rs = s.getResultSet();
int concurrency = rs.getConcurrency();
if(concurrency == ResultSet.CONCUR_UPDATABLE)
{
System.out.println("rs is updatable");
} else {
System.out.println("rs Not updatable");
}
s.close();
conn.close();
} //close try
catch (Exception ex) {
ex.printStackTrace();
} //close catch
} //close main method
} //close dbAccess class
the output is that rs is Not updatable. So I cannot update or insert rows in the resultset.
The code posted is the operative part of a larger project, where UCanAccess can read the table and put the contents in a jList and jTextarea, with formatting. When I started writing code to update or add a new record, I ran into the problem.
I apologize if this is a bit long.
Anybody have an idea what I'm missing or doing wrong?
BTW, this is one of my 2 fav sites for good, usable Java answers.
UPDATE:
Got an idea from old co-worker, the original database may have been copied from an original Access97 db. to a 2000 db. I had used 2013 Repair and Compact to make "new" 2002 and 2013 db's. Access must retain '97 type even when doing what I did. So, I created a new 2013 dummy db to test, and UCanAccess will report resultset as updatable. I will try to recreate the record data of the current db in a new database file, and see if that works. I'm hoping this is the problem, since UCanAccess doesn't support updatability with Access97 db's. I'll let ya'll know what I find.
Thanks.
I had used 2013 Repair and Compact to make "new" 2002 and 2013 db's. Access must retain '97 type even when doing what I did. So, I created a new 2013 dummy db to test, and UCanAccess will report resultset as updatable.
The "Compact and Repair Database" feature in Access does not change the database file version. If you have (what you suspect to be) an older-version database file then you should use the "Save Database As" feature under "File > Save & Publish" * to convert the database file to a newer version.
* (... at least that's where it is in Access 2010.)
Well, after a nice weekend of eating brats and drinking good beer at Germanfest, I finally got things working. I decided to scrap the MS Access db and put the 472 records in a SQLite db. With that, I was able to get PreparedStatements to work to display the records in a jList and JTextArea, add a new record and update a couple fields in an existing record within the same run of the test application. Did it both as a command line run GUI and from NetBeans 8.0, so I think my problems are solved. After a couple of summer projects get done, I'll get back to re-writing the original VB app using Java.
Thanks Gord, and everyone here.
I want to insert every filename of my local drive into a mysql database.
When I execute this code, it start perfectly.
Code that reads the directory for filenames:
public void main(String[] args)throws IOException {
JOptionPane.showMessageDialog(null, "IT MAY TAKE SOMETIME TO LOAD \n PLEASE WAIT FOR CLOSING POPUP!!");
String s="D:\\";
Path startingDir = Paths.get(s);
String pattern="*";
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, finder);
JOptionPane.showMessageDialog(null,"close\n NOW PLEASE CLICK\nSEARCH MY FILE! BUTTON");
This is the code to insert the results into the database:
public void find(Path file) {
Path name = file.getFileName();
String st = file.toString();
if (name != null && matcher.matches(name)) {
try {
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/login","root","");
conn.createStatement();
String query =" INSERT INTO `search`(`path`) VALUES (?)";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1,st );
pst.execute();
//myst.executeUpdate(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, e);
}
After some time, the scripts stops with this exception
com.mysql.jdbc.exception.jdbc4.MYSQLNonTransientConnectionException:
Data source rejected establishment of connection,
message from server:"Too Many connections"
Is there any way to solve this problem?
For every insert you create a new connection. If you keep doing this they build up and eventually you run out of connections to the database. This limit could be quite small e.g. 20.
Instead you can either
close the resources you have used. This means closing the PreparedStatement and the Connection
or more efficiently, create one Connection and one PrepareStatement ever and reuse it. The saves having to create and clean up resources which can be expensive (unless the driver does this recycling for you)
the easy fix would be to close the connection after you execute the query.
pst.close();
conn.close();
this should get the job done.
But it'd be better to reuse the connection.
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.
for a school database project we are making a database program (user GUI and the database). Using Microsoft Access 2010 I created the database and populated it with some sample data, and saved it in .mdb format and placed it in my project folder.
When running it in eclipse the following code works fine, connects and even retrieves the query. However I find that I am unable to export the code to a jar and run it (which is required for the project, give them a working copy of your program on a CD or flash drive), and I'm also unable to port the code over to Netbeans to have it work, as well as trying to compile on a Linux machine.
I assume this is a problem with including drivers or trying to use Microsoft access. The error I get when running the jar or running on Netbeans is given below the code. So I ask either how do I include drivers to make the program portable, or how else can I approach this problem?
Thanks in advance
import java.sql.*;
public class JDBCTest {
static Connection connection;
static Statement statement;
public static void main(String args[]){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=TLDATABASEDBM.mdb";
connection = DriverManager.getConnection( database ,"","");
buildStatement();
executeQuery();
}catch(Exception e){
e.printStackTrace();
System.out.println("Error!");
}
}
public static void buildStatement() throws SQLException {
statement = connection.createStatement();
}
public static void executeQuery() throws SQLException {
boolean foundResults = statement.execute("SELECT * FROM tblStaff AS x WHERE City='Calgary'");
if(foundResults){
ResultSet set = statement.getResultSet();
if(set!=null) displayResults(set);
}else {
connection.close();
}
}
public static void displayResults(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columns=metaData.getColumnCount();
String text="";
while(rs.next()){
for(int i=1;i<=columns;++i) {
text+=""+metaData.getColumnName(i)+":\t";
text+=rs.getString(i);
//text+="</"+metaData.getColumnName(i)+">";
text+="\n";
}
text+="\n";
}
System.out.println(text);
}
}
The error mentioned above:
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(JdbcOdbc.java:3073)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(JdbcOdbcConnection.java:323)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:174)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at tldatabase.DataConnect.makeConnection(DataConnect.java:35)
at tldatabase.Main.main(Main.java:24)
I know the post was years ago but I felt like answering the question for those who are just experiencing this right now. It took me a while to know the answer to the question so here's the solution:
http://wiki.netbeans.org/FaqSettingHeapSize
Follow the "Running the 32-bit JVM".
All you have to do is find the netbeans.conf in the installation folder of your netbeans and change the directory from something like this:
netbeans_jdkhome="C:\Program Files\Java\jdk1.6.0_24"
to this:
netbeans_jdkhome="C:\Program Files (x86)\Java\jdk1.6.0_21"
The problem is netbeans might be running in 64 bit but MS Access only support 32-bit. So doing this would hopefully solve the problem. Also make sure to install this:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=23734
The main problem lies in the line:
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=TLDATABASEDBM.mdb";
Make sure that the .mdb file is in the correct directory.
Check the file extension as .mdb or .mdbacc.
Also, if you want to use the same DSN every time, it is better to add the DSN(Data Source Name) into the respective system on which the mdb is stored.
I think that your app do not see TLDATABASEDBM.mdb in current directory. You can give full path to this file in connection string or add system DSN in ODBC Manager and then connect to it with connection string like: jdbc:odbc:TLDATABASEDBM
Honestly, I dont like what I am going to say... but, it solved the same issue for me... mysteriously... :(((
on the line where you are defining the database variable, I changed ...(.mdb)... into ...(.mdb, *.accdb)...
All the best for figuring out what difference that made!
package javaapplication1;
import java.sql.*;
public class MSaccess_archive {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to a MS Access DB you have on your machine
String filename = "mdbTEST.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;}"; // add on to the end
// now we can get the connection from the DriverManager
Connection con = DriverManager.getConnection( database ,"","");
Statement stmt = con.createStatement();
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Result that came from our query
if (rs != null)
while ( rs.next() ){
System.out.println("Name: " + rs.getInt("Age") + " ID: "+rs.getString("Course"));
}
stmt.close();
con.close();
}
catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}