java.sql import not working - java

My .getTables and .prepareStatement are not working. I thought I only had to import the java.sql.* for these to work. Please let me know what else I need to do. Thank you for your time. It says "cannot find symbol" next to both lines and will not compile.
import edu.lcc.citp.inventory.Product;
import java.sql.DriverManager;
import javax.jms.Connection;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.jms.JMSException;
public class DatabaseProductDao implements DataAccessObject<Product> {
Connection con;
public DatabaseProductDao() throws SQLException, JMSException, ClassNotFoundException {
Class.forName("cockeb.org.apache.derby.jdbc.ClientDriver");
try (Connection con = (Connection) DriverManager.getConnection("jdbc:derby://localhost:1527/store;create=true")) {
boolean exists = con.getMetaData().getTables(null, null, "PRODUCT", null).next();
if (exists) {
System.out.println("Table Exists");
} else {
String createDml = "CREATE TABLE PRODUCT (UPC VARCHAR(25), SHORT_DETAILS VARCHAR(50), LONG_DETAILS VARCHAR(5000), PRICE DECIMAL(10,2), STOCK INTEGER, PRIMARY KEY (UPC))";
PreparedStatement createStatement = con.prepareStatement(createDml);
createStatement.execute();
}
} catch (SQLException e) {
System.out.println("Can Not Connect At This Time");
}
}

The problem is with imports.
You imported javax.jms.Connection which is obiously wrong. Just delete it.
What you wanted is Connection class from java.sql (java.sql.Connection) package.
Also I do not suggest to use wildcards (.*) in import but pick specific class you actually use. In your case:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

You need to add the following imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
instead of the one you are using

I'd suggest that you remove these lines:
import javax.jms.Connection;
import javax.jms.JMSException;
...as it's probably not the Connection class that you actually intended on importing. Your java.sql.* import should grab the correct one once you remove the lines above.

Some of your imports are wrong. You need below to make it work.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Connection;
One step ahead I would like to suggest you to have a separate class to establish the database connection. This way you don't need to repeat the same code again.
Sample code. (Do changes for this as appropriate.)
for instance have a DatabaseCon.java class in your project
package classes;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class DatabaseCon {
private static Connection c;
private static void connect()
throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "db_url/db";
c = DriverManager.getConnection(url, "username", "pass");
}
public static PreparedStatement prepareState(String sql)
throws Exception {
if (c == null) {
connect();
}
return c.prepareStatement(sql);
}
}
This can then be called by
public void yourMethod() {
PreparedStatement p = null;
try {
p = DatabaseCon.prepareState("Your_query");
............
} catch (Exception e) {
//catch it
} finally {
//do the final stuff
}
}
Note This way is good if it is a fairly big project as you've mentioned.

You have imported a few wrong classes for use.
import java.sql.DriverManager;
import javax.jms.Connection;
import java.sql.*;
import javax.jms.JMSException;
The jms imports are of no use; you have imported them in vain, which is causing issues in your program.
The main import required is java.sql.*,
the application will work correctly if you just remove the jms imports.
But, the best practice to import classes is to specify the specific class from which you are using the element/method.
See here for the reason Single import vs package import

Related

How to fix error: java.sql.SQLException: No suitable driver found for https://my_account.snowflakecomputing.com/?

I have this code:
package routines;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Properties;
public class SnowflakeDriverExample {
public static void main() throws Exception
{
System.out.println("Create JDBC connection");
Connection connection = getConnection();
System.out.println("Done creating JDBC connectionn");
}
private static Connection getConnection()
throws SQLException
{
try
{
Class.forName("net.snowflake.client.jdbc.SnowflakeDriver");
}
catch (ClassNotFoundException ex)
{
System.err.println("Driver not found");
}
// build connection properties
Properties properties = new Properties();
properties.put("user", "my_user");
properties.put("password", "my_password");
properties.put("db", "my_db");
properties.put("schema", "my_schema");
// create a new connection
String connectStr = System.getenv("SF_JDBC_CONNECT_STRING");
// use the default connection string if it is not set in environment
if(connectStr == null)
{
connectStr = "https://my_account.snowflakecomputing.com/";
}
return DriverManager.getConnection(connectStr, properties);
}
}
now, when I call:
SnowflakeDriverExample.main();
I get this error:
Exception in component tJava_1 (j_example)
java.sql.SQLException: No suitable driver found for https://my_account.snowflakecomputing.com/
when I iterated over drivers and printed them- I got this one:
net.snowflake.client.jdbc.SnowflakeDriver
looks like I have the correct snowflake driver, and I the connectionStr is my actual snowflake url.
so what's the problem?
ok.
the problem was my connectionStr, which was:
connectStr = "https://my_account.snowflakecomputing.com/";
and should be:
connectStr = "jdbc:snowflake://my_account.snowflakecomputing.com/";
now everything is fine. thanks a lot!

How can I set the directory of a MongoDB database in a Java application?

I recently decided to learn the foundamentals of using MongoDB in Java applications but I have some problems and doubts to resolve. I hope someone can help me.
I wrote a little Java application to read and write data in a local Mongo database (I'm using mongo-java-driver-3.3.0.jar on Windows 10).
I have installed MongoDB in the directory C:\Program Files\MongoDB.
Can anyone tell me if is possible to create my test database in a specific directory (for example D:\Database)? Thank you.
package test;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoDatabase;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC
{
public static void main( String args[] )
{
try
{
// Connection to the MongoDB server
MongoClient mongoClient = new MongoClient("localhost" , 27017);
// Connection to the database
MongoDatabase db = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
}
catch(Exception e)
{
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

load csv file to oracle database

Hi I wanted to load csv file in Oracle database using java but what I am getting error like "ora-00900 invalid sql statement". I am using oracle Database 11g Enterprise Edition. So I don't understand why it doesn't accept my load statement. Any help? Thanks in advance.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class test {
public static void main(String[] args){
test t=new test();
t.inserintoDb("C:\\Users\\fiels\\2.csv");
}
public void inserintoDb(String path){
Connection conn=null;
Statement stmt=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=(Connection) DriverManager.getConnection(
"jdbc:oracle:thin:#address:orcl","user","password");
stmt=conn.createStatement();
String select1="truncate table table1";
stmt.execute(select1);
String select2="LOAD DATA INFILE'" +path+"' INTO TABLE table1 FIELDS TERMINATED BY ',' (customer_nbr, nbr)";
stmt.execute(select2);
}catch(Exception e){
e.printStackTrace();
}
}
}
Does infile works on Oracle? It seems that only on MySql.. The SQL Loader alternative is really fast. Check the official documentation to see how to config it:
As the question states that you want to use Java here is the help for calling the SQL Loader from Java. It bassically uses a Runtime but depends on the operating system:
String[] stringCommand = { "bash", "-c", "/usr/bin/sqlldr username/password#sid control=/path/to/sample.ctl"};
Runtime rt = Runtime.getRuntime();
Process proc = null;
try {
proc = rt.exec(stringCommand);
}catch (Exception e) {
// TODO something
}finally {
proc.destroy();
}
But if you just want to load some table for your personal use you wont need java. You can call it from a .bat file.

Addition of web service access in servlet unrecognized/unresolved; seen as "type".

I am trying to create a simple servlet (tomcat) that accesses a database, then a USDA web service. I've successfully deployed/tested the database connectivity. When I added the web service access, eclipse reports the problem: AwdbWebService_Service cannot be resolved to a type.
The hour is late... I just don't see why this won't resolve as a service instance.
The error is tripped by this line:
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
Here is the code:
package localdomain.localhost;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL; //added for usda webservice
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.namespace.QName; // added for usda webservice
import usda.nrcs.wcc.awdbWebService.*;
#WebServlet(value = "/MyServlet")
public class MyServlet extends HttpServlet {
// use this for usda reservoir station values later
static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
protected final Logger logger = Logger.getLogger(getClass().getName());
#Resource(name = "jdbc/mydb", lookup = "jdbc/mydb")
private DataSource dataSource;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
logger.info("Init");
System.out.println(getClass().getName() + ".init");
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
PrintWriter writer = resp.getWriter();
writer.println("<html>");
writer.println("<head><title>MyServlet</title></head>");
writer.println("<body><h1>MyServlet</h1>");
writer.println("<h2>DataSource</h2>");
Connection conn = null;
try {
writer.println("Datasource: " + dataSource + "<br/><br/>");
conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select 1");
while (rst.next()) {
writer.println("Resultset result: " + rst.getString(1) + "<br/><br/>");
}
rst.close();
stmt.close();
conn.close();
writer.println("SUCCESS to access the datasource");
// Now try accessing usda
URL wsURL = new URL("http://www.wcc.nrcs.usda.gov/awdbWebService/services?wsdl");
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
m_webService = lookup.getAwdbWebServiceImplPort();
} catch (Exception e) {
e.printStackTrace(writer);
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
writer.println("</body></html>");
}
}
For those following this thread:
The package statement at the start of the java classes I generated with wsimport begins with:
package gov.usda.nrcs.wcc.awdbWebService
My import statement however looked like this:
import usda.nrcs.wcc.awdbWebService.*;
In essence I placed the source # the wrong level and defined the build config to point incorrectly for the package references in the java classes. I removed the build reference, moved the tree to begin pointing on the gov level. Now that there wasn't a mismatch, the unresolved type error vanished.

Full Dataset Export blank dataset

I have a database in libreoffice Base (Debian) which I need to export the tables as an xml file. I have created a piece of Eclipse Java code which is as follows:
package NewDB;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.dataset.DataSetException;
public class ExtractTestDataSet {
public static void main(String[] args) throws Exception {
// database connection
Class driverClass = Class.forName("org.hsqldb.jdbcDriver");
Connection jdbcConnection = DriverManager.getConnection "jdbc:hsqldb:/home/debian/Documents/database.odb", "sa", "");
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
// full database export
IDataSet fullDataSet = connection.createDataSet();
FlatXmlDataSet.write(fullDataSet, new FileOutputStream("/home/debian/Documents/fulldataset.xml"));
}
}
After looking at the DBunit pages and other various sites this code should be correct; the database is populated, the connections are valid, there are no warnings or errors in the code, however when the xml file is created the only content is as follows:
<?xml version='1.0' encoding='UTF-8'?>
<dataset/>
Does anyone have any ideas as to why the dataset is not being exported?
Thanks
Turns out that the .odb database was connected to a different backend, explaining the blank dataset.

Categories