Using MS-SQL With Maven2, Netbeans on a (Mac or Linux) - java

Looking for advice or a bit of help, to point me in the right direction.
I need to connect to a Microsoft SQL Server from a Java program, however, the drivers must be available in maven2 and work with NetBeans.
Any advice? (pointer to an example would be great) (Suicide is no longer an option)
Edit: I've found JTDS- is this a good solution?
Edit 2: Looks like it works... Here is how I have it configured...
Pom file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.steward.ccd</groupId>
<artifactId>amalgainterface</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>amalgainterface</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.ini4j</groupId>
<artifactId>ini4j</artifactId>
<version>0.5.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
</project>
Java File
import java.sql.*;
import org.ini4j.*;
import java.util.*;
import java.io.File;
public class AmalgaInterface {
public static void main(String[] args) {
// MS-SQL Parameters
String db_name = "xxxx";
String db_hostname = "xxxx";
String db_port = "1433";
String db_userid = "xxxx";
String db_password = "xxxx";
String db_timeout = "10";
// Check the Configuration file, and replace all service reference as required.
// Get configuration
String configFile = "/etc/test.conf";
// Load data from INI files
Ini ini = null;
try {
ini = new Ini(new File(configFile));
db_name = ini.get("database", "name");
db_hostname = ini.get("database", "host");
db_userid = ini.get("database", "user");
db_password = ini.get("database", "pass");
db_port = ini.get("database", "port");
db_timeout = ini.get("database", "dbtimeout");
} catch (Exception ex) {
System.out.println("Cannot load the configuration file");
}
// Create the connection string
String db_connect_string = "jdbc:jtds:sqlserver://" + db_hostname + ":" + db_port + "/" + db_name + ";socketTimeout=" + db_timeout;
// setup connection
Connection connection = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connection = DriverManager.getConnection(db_connect_string, db_userid, db_password);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
// clean up
if (connection != null) {
try {
connection.close();
} catch (Exception ex) {
}
}
}
}

Try JTDS
It's a type 4 jdbc driver and I believe it's available via maven repository.

Related

java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver when using Maven Dependency

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>7.0.47</version>
</dependency>
Above is the maven dependency I'm using.
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#//ip:port:ora11g");
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("un");
p.setPassword("pw");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors(
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
"org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
DataSource datasource = new DataSource();
datasource.setPoolProperties(p);
Connection con = null;
try {
con = datasource.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from user");
int cnt = 1;
while (rs.next()) {
System.out.println((cnt++)+". Host:" +rs.getString("Host")+
" User:"+rs.getString("User")+" Password:"+rs.getString("Password"));
}
rs.close();
st.close();
} finally {
if (con!=null) try {con.close();}catch (Exception ignore) {}
}
And above is my database querying test code snippet.
When I'm executing the program I'm getting "java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver" exception.
I searched for the issue and read that I have to "make sure oracle jdbc jar is in the classpath". I'm not sure why do I have to set it manually or is it actually required.
Use below dependency
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>
and use below code to connect with your oracle database.
Class.forName("oracle.jdbc.OracleDriver");
String dbURL1 = "jdbc:oracle:thin:{USER}/{PASSWORD}#{URL}:{PORT}:{DBNAME}";
//e.g. String dbURL1 = "jdbc:oracle:thin:tiger/scott#localhost:1521:productDB";
Connection conn1 = DriverManager.getConnection(dbURL1);
if (conn1 != null) {
System.out.println("Connected with connection #1");
}
I resolved the issue by adding the corresponding ojdbc.jar to the project.
It can be resolved by adding the mentioned maven dependency too (mentioned by Joy).
Note that you can download the 19.3 JDBC drivers from central maven

Java, Maven, connect SQL , no suitable driver

I am building a project using Netbeans IED, with java. The project is using maven and I am attempting to connect it to sql database which I am having issue's. The code works in java but not with maven.
Here the error:
No suitable driver found for jdbc:derby://localhost:1527/Database
Java Code:
public class DatabaseTest {
public static Connection ConnectionObj = null;
public static Statement SqlStatement = null;
public static ResultSet Sqlresult = null;
public static ResultSetMetaData MetaData = null;
public static String query = "Select * from Wallet";
public static String url = "jdbc:derby://localhost:1527/Database";
public static String user = "ABM";
public static String pass = "password2";
public static void main(String[] args) {
try {
//Allows you to connect the database
ConnectionObj = DriverManager.getConnection(url, user, pass);
SqlStatement = ConnectionObj.createStatement();
Sqlresult = SqlStatement.executeQuery(query);
MetaData = Sqlresult.getMetaData();
System.out.println("Connection worked");
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Prom depency's:
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.14.1.0</version>
</dependency>
https://gyazo.com/8937aada3bd4a8f5b108b5dc9b386dd7
This part of your POM file is incorrect:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
Your program is attempting to use JDBC to connect to a Derby database, so you should be using a Derby JDBC driver, not a MySQL JDBC driver.
Replace the above with the following:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.14.1.0</version>
</dependency>
(Use the same version as your main Derby version ...)
The code works in Java but not with Maven.
Curious. Perhaps you are setting the runtime classpath correctly in the Java case.

Maven not including jar files in classpath during packaging

I'm getting started with Maven and have come across a problem I'm unable to resolve. It seems the jar files required for my applicaiton to run are not in the classpath. Should Maven not be taking care of this during mvn package?
When I run mvn package, I get error:
[ERROR] /home/dev/Desktop/maventest/my-app/src/main/java/com/mycompany/app/App.java:[79,9] cannot find symbol
symbol: class UpnpService
location: class com.mycompany.app.App
[ERROR] /home/dev/Desktop/maventest/my-app/src/main/java/com/mycompany/app/App.java:[79,39] cannot find symbol
symbol: class UpnpServiceImpl
location: class com.mycompany.app.App
The sample code does say: "You need cling-core.jar and its dependencies (seamless-*.jar files) on your classpath to build and run this code. "
But is this not something maven should take care of? If not, how do I include these files?
Here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>my-app</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>4thline-repo</id>
<url>http://4thline.org/m2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.fourthline.cling</groupId>
<artifactId>cling-core</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
</project>
And here is sample code I'm trying to run:
package com.mycompany.app;
import org.fourthline.cling.model.message.header.STAllHeader;
import org.fourthline.cling.model.meta.LocalDevice;
import org.fourthline.cling.model.meta.RemoteDevice;
import org.fourthline.cling.registry.Registry;
import org.fourthline.cling.registry.RegistryListener;
/**
* Runs a simple UPnP discovery procedure.
*/
public class App {
public static void main(String[] args) throws Exception {
// UPnP discovery is asynchronous, we need a callback
RegistryListener listener = new RegistryListener() {
public void remoteDeviceDiscoveryStarted(Registry registry,
RemoteDevice device) {
System.out.println(
"Discovery started: " + device.getDisplayString()
);
}
public void remoteDeviceDiscoveryFailed(Registry registry,
RemoteDevice device,
Exception ex) {
System.out.println(
"Discovery failed: " + device.getDisplayString() + " => " + ex
);
}
public void remoteDeviceAdded(Registry registry, RemoteDevice device) {
System.out.println(
"Remote device available: " + device.getDisplayString()
);
}
public void remoteDeviceUpdated(Registry registry, RemoteDevice device) {
System.out.println(
"Remote device updated: " + device.getDisplayString()
);
}
public void remoteDeviceRemoved(Registry registry, RemoteDevice device) {
System.out.println(
"Remote device removed: " + device.getDisplayString()
);
}
public void localDeviceAdded(Registry registry, LocalDevice device) {
System.out.println(
"Local device added: " + device.getDisplayString()
);
}
public void localDeviceRemoved(Registry registry, LocalDevice device) {
System.out.println(
"Local device removed: " + device.getDisplayString()
);
}
public void beforeShutdown(Registry registry) {
System.out.println(
"Before shutdown, the registry has devices: "
+ registry.getDevices().size()
);
}
public void afterShutdown() {
System.out.println("Shutdown of registry complete!");
}
};
// This will create necessary network resources for UPnP right away
System.out.println("Starting Cling...");
UpnpService upnpService = new UpnpServiceImpl(listener);
// Send a search message to all devices and services, they should respond soon
upnpService.getControlPoint().search(new STAllHeader());
// Let's wait 10 seconds for them to respond
System.out.println("Waiting 10 seconds before shutting down...");
Thread.sleep(10000);
// Release all resources and advertise BYEBYE to other UPnP devices
System.out.println("Stopping Cling...");
upnpService.shutdown();
}
}
The example code is from: http://4thline.org/projects/cling/core/manual/cling-core-manual.xhtml#chapter.GettingStarted
Would really appreciate your help.
Looks like the example I was using was missing import statements:
import org.fourthline.cling.UpnpService;
import org.fourthline.cling.UpnpServiceImpl;
Maven takes care of the dependencies that you declare in pom.xml, in order to resolve your issue you should add the cling-core dependency in pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>my-app</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>4thline-repo</id>
<url>http://4thline.org/m2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.fourthline.cling</groupId>
<artifactId>cling-core</artifactId>
<version>2.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.fourthline.cling/cling-core -->
<dependency>
<groupId>org.fourthline.cling</groupId>
<artifactId>cling-core</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
</project>
Replace your pom.xml with the above and see maven downloads the jars including all its dependencies.

Servlet with JDBC [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 5 years ago.
I have a problem with my progect. Files of progect:
House.class
public class House implements Serializable {
//properties -------------------------------------------------------------
private String price;
private String square;
private String RoomNumbers;
//------------------------------------------------------------------------
//getters - settersm Object overriding.... -----------------------------
HouseDAO.class
public class HouseDAO {
Connection connection;
final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb2";
final String DB_USER = "root";
final String DB_PASSWORD = "root";
public HouseDAO(Connection connection) {
this.connection = connection;
}
public List<House> getList() {
List<House> houses = new ArrayList<>();
try {
connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
System.out.println("Connection available");
PreparedStatement ps = connection.prepareStatement("SELECT Square, RoomNumbers, Price FROM houses WHERE District = 'Dnepr'");
ResultSet rs = ps.executeQuery();
while (rs.next()){
House house = new House();
house.setSquare(rs.getString("Square"));
house.setRoomNumbers(rs.getString("RoomNumbers"));
house.setPrice(rs.getString("Price"));
houses.add(house);
}
}catch (Exception ex){
System.out.println("SQL exceprion");
ex.printStackTrace();
}
return houses;
}
}
and Servlet:
HousesBaseServlet
#WebServlet("/post")
public class HosesBaseServlet extends HttpServlet {
Connection conn;
private HouseDAO houseDAO;
#Override
public void init(){
houseDAO = new HouseDAO(conn);
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
//choice from html form
// String choice = request.getParameter("district");
try {
List<House> houses = houseDAO.getList();
request.setAttribute("houses", houses);
request.getRequestDispatcher("/houses.jsp").forward(request,response);
}catch (Exception ex ) {
System.out.println("Fail to connect with base");
ex.printStackTrace();
}
}
}
I was read some solutiotuns, but it doesn't help. The problem in two exceptions:
SQL exceprion java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/mydb2
I try to add:
Class.forName("com.mysql.jdbc.Driver");
to my code, and add mysql connector jar to my project, but it throws exception:
SQL exception java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Second exception:
JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core
cannot be resolved in either web.xml or the jar files deployed with
this application Fail to connect with base
Here is my pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
,
JSP taglib:
%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %
and project structure:
[project structure][1]
Project structure - artifacts
In project structure -> libraries i have all jars.
Since you are using IntelliJ I believe you might need to add the libraries to the artifact because from my experience Intellij adds the maven dependencies to the Classpath but not to the artifact.
Make sure you go to File -> Project Structure -> Artifacts and then add all the libraries from the available side to the artifact.
But you need to register the driver before getting the connection otherwise it doesn't work either way :
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
Hope this helps.

Exception with com.mysql.jdbc.Driver

i'm trying run code
public static Connection getConnection() throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull [root on Default schema]");
} catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null,e.toString());
}
return cn;
}
but i get the exception:
with the dialog:
I have added the divier :mysql-connector-java-5.1.36-bin.jar in this project.
What am I doing wrong?
Add mysql connector jar to your project classpath.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

Categories