I'm trying to make a java desktop database application, using the derby embedded database, I'm having some issues that I can't quite fix, and I've searched (a lot) for the answers, found some, but they couldn't solve my problem, so I decided to make a question myself. I made the database on netbeans, jut like a whole bunch of tutorials teach, downloaded the derby.jar and added to the library on the project, but then when I try to insert some data in the database's table that I created is says that the table doesn't exist.
I'm pretty sure i'm missing something really stupid, but I can't figure it out by myself, so any help will be very much appreciate. I'm new to all this java database development, I had only created local databases on c#
PS: The schema is the 'APP' one, I tried using "INSERT INTO APP.PACIENTE (ID, NOME) VALUES (1, 'victor')" but that didn't work either
public class BancoDados {
private static String url = "jdbc:derby:MeuBancoDados;create=true";
private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
static Connection conn;
static Statement sta;
public static void insert() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
conn = null;
sta = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
sta = conn.createStatement();
sta.executeUpdate("INSERT INTO PACIENTE (ID, NOME) VALUES (1, 'victor')");
sta.close();
conn.close();
System.out.println("Inserido com sucesso!");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
}
}
I get This error:
Exception in thread "main" ERROR 42X05: Table 'PACIENTE' does not exist.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLModStatementNode.verifyTargetTable(Unknown Source)
at org.apache.derby.impl.sql.compile.InsertNode.bind(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.executeUpdate(Unknown Source)
at projcad.BancoDados.insert(BancoDados.java:31)
at projcad.projcad.main(projcad.java:8)
Java Result: 1
Table 'PACIENTE' does not exist.
This is because in database you have not created the PACIENTE table.
Create it.
Related
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 know this has been asked before but I really can't get this to work and as far as I can see I've followed all the steps.
I'm using Eclipse.
So I downloaded the Microsoft SQL Driver sqljdbc v4.0.
I created a new project and class. I edited the build path by adding the .jar file to the libraries.
I typed the following code:
package com.test.sql;
import java.sql.*;
public class Connect
{
public static void main (String[]args)
{
Connection con = null;
String conURL = "jdbc:sqlserver://localhost; databaseName=AnotherTestDB;";
try
{
con = DriverManager.getConnection(conURL);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I got the following error:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost; databaseName=AnotherTestDB;
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.test.sql.Connect.main(Connect.java:11)
A bit more research and I was told put it in the java /lib/ext and reference it from there.
Nothing changed.
Any help?
Thanks.
Normally you need to register the driver before accessing to it:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Try with something like this:
String DRIVER = “oracle.jdbc.driver.OracleDriver”;
String DBURL = “jdbc:oracle:thin:#jiplc0.si.ehu.es:1512:Erreala”;
String UID = “USERNAME”;
String PWD = “PASSWORD”;
Driver kontrolatzailea = (Driver) (Class.forName(DRIVER).newInstance());
DriverManager.registerDriver(kontrolatzailea);
DefaultContext test = new DefaultContext(DBURL, UID, PWD, false);
DefaultContext.setDefaultContext(test);
Thanks for the responses.
I had both the sqljdbc4.jar and sqljdbc.jar referenced. The version of Java I am using requires that I use sqljdbc4.jar but it was being overwritten by sqljdbc.jar so I removed it.
I also changed my code to this:
public static void main (String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://nameMyLaptop//SQLEXPRESS";
Connection con = DriverManager.getConnection(connectionUrl);
}
//Insert catches
}
Apparently I didn't have to change the code but its not giving me that error now. I'm getting a new one but that's unrelated to my question.
Thanks for your time and responses.
You have to add the SQL JDBC Driver in your project libraries. download jtds.jar and add to your libraries. And follow the code below.
public static void main (String[] args) throws Exception{
Connection conn=null;
String url="jdbc:jtds:sqlserver://YourServerIp:1433/dbName";
String username="sa";
String password="****";
String driver="net.sourceforge.jtds.jdbc.Driver";
// Step 1: Load the JDBC driver.
Class.forName(driver);
// Step 2: Establish the connection to the database.
conn= DriverManager.getConnection(url, username,
password);
}
Here you have to follow two steps......
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.
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.