I have written sql server connection part.When I run this code, i got this error.
Error Trace in getConnection() : com.microsoft.jdbc.sqlserver.SQLServerDriver
Error: No active Connection
java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.sample.DB.getConnection(DB.java:30)
at com.sample.DB.displayDbProperties(DB.java:49)
at com.sample.DB.main(DB.java:85)
I have installed sql sever 2008 R2. I serached google I couldn't find the solution....
This is my code
public class DB {
private java.sql.Connection con = null;
private final String url = "jdbc:microsoft:sqlserver://";
private final String serverName= "localhost";
private final String portNumber = "1433";
private final String databaseName= "XONTHOMass_User";
private final String userName = "sa";
private final String password = "xont#123";
// Informs the driver to use server a side-cursor,
// which permits more than one active statement
// on a connection.
private final String selectMethod = "cursor";
private String getConnectionUrl(){
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
private java.sql.Connection getConnection(){
try{
System.out.println("========1========");
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
System.out.println("==== 2=====");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties(){
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
try{
con= this.getConnection();
if(con!=null){
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
rs = dm.getCatalogs();
while(rs.next()){
System.out.println("\tcatalog: "+ rs.getString(1));
}
rs.close();
rs = null;
closeConnection();
}else System.out.println("Error: No active Connection");
}catch(Exception e){
e.printStackTrace();
}
dm=null;
}
private void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
DB myDbTest = new DB();
myDbTest.displayDbProperties();
}
}
Please help me..I did this application using the eclipse.I have put jar file also `sqljdbc4.jar'...
Please help me
You receive the exception:
java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
That means your program cannot find the Driver and therefore not even try to connect to the database.
Mircosoft has an article on How to Get Started with Microsoft JDBC:
The Microsoft SQL Server 2000 driver for JDBC .jar files must be listed in your CLASSPATH variable. The CLASSPATH variable is the search string that Java Virtual Machine (JVM) uses to locate the JDBC drivers on your computer..
As a complete guess, you have installed Express Edition (you should always mention the edition, not just the version) but you have not enabled TCP/IP support using the SQL Server Configuration Manager. By default, Express Edition does not have any network protocols enabled, so connecting over TCP/IP will not work unless you enable it first.
I think this is the driver that you need to use
com.microsoft.sqlserver.jdbc.SQLServerDriver
not com.microsoft.jdbc.sqlserver.SQLServerDriver
Just do one thing go to http://www.java2s.com/Code/Jar/s/Downloadsqljdbcjar.htm and download the sqljdbc jar and use it in your program.
Related
I have a JAR file that doesn't connect to the database even though it connects just fine in the IDE. I'm stuck and I don't know where to go from here. I am using Java 8 in IntelliJ trying to run SQLite.
Here is the code for the Database class.
private static Connection connection = null;
private static boolean connected = false;
static void connect() {
String driver = "org.sqlite.JDBC";
String db = "schedulerDB";
String path = "lib\\";
String url = "jdbc:sqlite:";
try {
Class.forName(driver);
connection = DriverManager.getConnection(url + path + db);
printInfo("Connected to database : " + db);
connected = true;
} catch (SQLException e) {
printError(1100, "Could not connect to database", e);
} catch (ClassNotFoundException e) {
printError(1101, "Driver not found error", e);
}
}
When I run the JAR file in the terminal, I get:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
Please help me.
Added e.printStackTrace(); as requested:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.throwex(DB.java:918)
at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
at org.sqlite.core.NativeDB.prepare(NativeDB.java:134)
at org.sqlite.core.DB.prepare(DB.java:257)
at org.sqlite.jdbc3.JDBC3Statement.execute(JDBC3Statement.java:52)
at scheduler.Database.query(Database.java:337)
at scheduler.User.buildList(User.java:42)
at scheduler.User.<clinit>(User.java:85)
at scheduler.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Unknown Source)
Change the value of url to
url = "jdbc:sqlite::resource:"
Your exception is actually caused by a MalformedURLException. The reason you are getting this is because lib\schedulerDB is not a valid URL.
URLs must use forward slashes (/), on all systems—even Windows. This is a requirement of the URI specification itself. (A URL is a type of URI, so every URL must conform to the rules of a URI.)
Making your URL valid should do the trick:
String path = "lib/";
I'm trying to execute SQL queries in query accelerator mode from Java using plain JDBC approach. That is, creating a connection from DriverManager and executed query. But it's getting failed throwing com.ibm.db2.jcc.am.SqlSyntaxErrorException
I set the special parameter in connection URL as mentioned in IBM docs for this.
Tables are already moved to IBM DB2 Analytics Accelerator (IDAA) server and I'm able to execute queries with accelerated mode from AQT tool (My DB client tool) and it is running ultra fast.
I've used db2jcc4 driver Type4 and the connection URL and Connection class is given below:
public class ConnectionManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionManager.class);
private static String url = "jdbc:db2://myIP:myPort/myDBName:specialRegisters=CURRENT QUERY ACCELERATION=ELIGIBLE";
private static String driverName = "com.ibm.db2.jcc.DB2Driver";
private static String username = "user";
private static String password = "pwd";
private static Connection con;
private static String urlstring;
public static Connection getConnection() throws SQLException, ClassNotFoundException {
try {
Class.forName(driverName);
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
throw ex;
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
throw ex;
}
return con;
}
}
Is there anything I missed or did wrong?
com.ibm.db2.jcc.am.SqlSyntaxErrorException: [jcc][10165][10051][4.24.92] Invalid database URL syntax: jdbc:db2://IP:Port/DBName:specialRegisters=CURRENT QUERY ACCELERATION=ELIGIBLE. ERRORCODE=-4461, SQLSTATE=42815
at com.ibm.db2.jcc.am.b6.a(b6.java:810)
at com.ibm.db2.jcc.am.b6.a(b6.java:66)
at com.ibm.db2.jcc.am.b6.a(b6.java:98)
at com.ibm.db2.jcc.DB2Driver.tokenizeURLProperties(DB2Driver.java:950)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:413)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:113)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at colruyt.spcpocxpsejb.util.ConnectionManager.getConnection(ConnectionManager.java:38)
at colruyt.spcpocxpsejb.util.TestUtility.testAOT(TestUtility.java:98)
at colruyt.spcpocxpsejb.util.TestUtility.main(TestUtility.java:25)
Caused by: java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at java.util.StringTokenizer.nextToken(StringTokenizer.java:377)
at com.ibm.db2.jcc.DB2Driver.tokenizeURLProperties(DB2Driver.java:938)
... 7 more
I am trying to connect Msaccess database with my java webapplication using the following code:
import java.sql.*;
public class connection {
public static void main(String[] args) {
try {
// Load MS accces driver class
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("loaded");
String url = "jdbc:odbc:OnboardingTT";
System.out.println("assigned");
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url,"","");
System.out.println("Connection Succesfull");
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}}}
But connection is not established. and the error is
loaded
assigned
Got an exception!
null
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.initialize(Unknown Source) at
sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
connect.connection.main(connection.java:18)
I also tried with
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ="+ "C:\\OnboardingTT.mdb";
Is this code correct or i have to do any changes in this please answer my question
Looks like something went wrong with the DB connection, maybe the DB is not online, maybe the user or the password are incorrect...
Please provide more info to help us to help you.
;-)
I downloaded and installed the uCanAccess jars by following instructions from here:
Manipulating an Access database from Java without ODBC
I'm learning how to use the microsoft access db for java and this is the coding I used
package Main.Net;
import java.sql.*;
public class DataBase {
Connection con;
Statement st;
ResultSet rs;
public DataBase() {
}
private void connect() {
try {
//String driver = "sun.jdbc.odbc.jdbcodbcdriver";
//Class.forName(driver);
String db = "jdbc:ucanaccess://C:/Users/MyUser/workspace/Connectors_DB.accdb";
con = DriverManager.getConnection(db);
st = con.createStatement();
String sql = "select * from Table";
rs = st.executeQuery(sql);
while(rs.next()) {
String username = rs.getString("Username");
String password = rs.getString("Password");
System.out.println(username + "\t" + password);
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DataBase().connect();
}
}
and when I run the java program, it comes with this error
Exception in thread "main" java.lang.NoSuchMethodError: org.hsqldb.DatabaseURL.parseURL(Ljava/lang/String;ZZ)Lorg/hsqldb/persist/HsqlProperties;
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at net.ucanaccess.jdbc.DBReference.getHSQLDBConnection(DBReference.java:354)
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:206)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Main.Net.DataBase.connect(DataBase.java:23)
at Main.Net.DataBase.main(DataBase.java:42)
error is at this code:
String db = "jdbc:ucanaccess://C:/Users/MyUser/workspace/Connectors_DB.accdb";
con = DriverManager.getConnection(db);
does it have something to do with the version of the hsqldb? because if it does I already tried downloading other versions of hsqldb and the same error appears
here are the jars I'm using:
ucanaccess-2.0.9.3.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.8.jar
so... how can I fix this?
The answers in this thread suggest, that there are multiple hsqldb-versions on your classpath. Maybe one of the other involved jars contains hsqldb as well? You can inspect them using a zip tool of your choice, or the command jar -tf foo.jar.
I want to create a webservice in Java that accesses a database stored in an external server. I have created a BeepWebService class containing the main information:
#WebService
public class BeepWebService {
private Connection conn = null;
private String url = "jdbc:mysql://xxxxxx.ipagemysql.com/";
private String dbName = "beep";
private String userName = "beep_user_name";
private String password = "pswrd";
private String db_str = " select Name beep.SW where Name = ";
public BeepWebService(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
}catch (Exception e) {
System.out.print("failed");
}
}
#WebMethod
public String returnFormat(#WebParam(name="input_value") String input){
String str = null;
String query = db_str+input;
try {
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
str = rs.getString(2);
System.out.println(str);
}
rs.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
}
I have then created the publisher class, named BeepWebServicePublisher:
public class BeepWebServicePublisher {
public static void main(String[] args){
System.out.println("Web Service initiating...");
Endpoint.publish("http://xxxxxx.ipagemysql.com/", new BeepWebService());
}
}
Unfortunately after compiling successfully the two classes and run the application, the output message is 'failed' (meaning that the connection couldn't be estabilished with the database) followed by an exception error. This is the complete output:
Web Service starting..
failedException in thread "main" com.sun.xml.internal.ws.server.ServerRtException: Server Runtime Error: java.net.BindException: Address already in use: bind
at com.sun.xml.internal.ws.transport.http.server.ServerMgr.createContext(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.HttpEndpoint.publish(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(Unknown Source)
at javax.xml.ws.Endpoint.publish(Unknown Source)
at com.BeepServicePackage.server.BeepWebServicePublisher.main(BeepWebServicePublisher.java:17)
Caused by: java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind(Native Method)
at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
at sun.net.httpserver.ServerImpl.<init>(Unknown Source)
at sun.net.httpserver.HttpServerImpl.<init>(Unknown Source)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(Unknown Source)
at com.sun.net.httpserver.HttpServer.create(Unknown Source)
... 6 more
As I am a novice in this field, can someone tell me if there is something wrong in the code or the problem may be with the server? Thanks!
Print out the entire stack trace; it'll give you more information than your "failed" message.
Where did you register the MySQL JDBC driver? I don't see it.
UPDATE: I'd recommend that you decompose the problem. Don't put the database code in the web service. Create an interface-based POJO that you can test off line. Get it working, then give an instance to the web service to use.
You have 99 problems, son. Start by fixing one at a time.
This is wrong:
private String db_str = " select Name beep.SW where Name = ";
You need a binding parameter:
private String db_str = " select Name beep.SW where Name = ?";
You need a PreparedStatement, not a Statement.
Then you want to bind the name you pass in.
You only have one column returned by the SELECT; why do you setString on column 2?
Wrong in so many ways.